How to plot a histogram with a custom distribution?

那年仲夏 提交于 2019-12-04 12:08:01

This should get what you want:

test <- read.table(textConnection("age popperc
0-5 8
5-14 18
14-18 8
18-21 5
21-25 6
25-35 12
35-45 11
45-55 11
55-65 9
65-75 6
75-85 4"),header=TRUE,stringsAsFactors=FALSE)

midval <- sapply(strsplit(test$age,"-"),function(x) mean(as.numeric(x)))
breakval <- strsplit(test$age,"-")
breakval <- as.numeric(c(sapply(breakval,head,1),tail(unlist(breakval),1)))
hist(rep(midval,test$popperc),breaks=breakval)

You can also define your own object of class histogram and then just plot that if you just want to plot the frequencies not the densities:

# define the histogram object and plot it
histres <- list(
breaks=breakval,
counts=test$popperc,
mids=midval,
xname="ages",
equidist = TRUE
)
class(histres) <- "histogram"
plot(histres)

As said in the comment use a barplot. You can specify width in a barplot

barplot(pcPop,  width = seq(0,85,5),space=0)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!