Creating a histogram with multiple data series using multhist in R

北慕城南 提交于 2019-12-04 10:42:06

Read the documentation of barplot to understand how to specify zero space:

multhist(year, xlab="Count", ylab="Frequency", main="", 
         cex.axis=1, col=c("dark gray", "light gray"), 
         breaks=seq(0,1600, by=200),
         space=c(0,0), beside=TRUE)

Here is an example with ggplot2 and theme_bw:

library(ggplot2)

ggplot(df, aes(x=count,group=year,fill=as.factor(year))) + 
  geom_histogram(position="identity", alpha=0.5, breaks=seq(0,1600, by=200),right=TRUE) +
  scale_fill_discrete(name="Year") +
  theme_bw(base_size=20) +
  xlab("values")

Or if you really want it like the plot from multhist (which is not as easy to interpret):

ggplot(df, aes(x=count,group=year,fill=as.factor(year))) + 
  geom_histogram(position="dodge", breaks=seq(0,1600, by=200),right=TRUE) +
  scale_fill_discrete(name="Year") +
  theme_bw(base_size=20) +
  xlab("values") +
  scale_x_continuous(breaks=seq(100,1500, by=200))

For superimposed histograms I prefer to use density plots. They're easier on the eyes, especially if you have thinner bins and more cases. With your data, one would get this.

ggplot(df, aes(x=count,group=year,fill=as.factor(year))) + 
  geom_density(position="identity", alpha=0.5, breaks=seq(0,1600, by=200),right=TRUE) +
  scale_fill_discrete(name="Year") +
  theme_bw() +
  xlab("values")

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