在R中使用multhist创建包含多个数据系列的直方图
我想在同一个图上创建一个包含多个数据系列的直方图。我能找到的最好的方法是在R中使用multhist创建包含多个数据系列的直方图,r,graphics,histogram,plotrix,R,Graphics,Histogram,Plotrix,我想在同一个图上创建一个包含多个数据系列的直方图。我能找到的最好的方法是multhist()。我希望打印的样式类似于hist(),虽然ggplot()也可以用于执行此任务,但图形样式不是我想要的 以下是一些示例数据: df <- structure(list(year = c(2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2
multhist()
。我希望打印的样式类似于hist()
,虽然ggplot()
也可以用于执行此任务,但图形样式不是我想要的
以下是一些示例数据:
df <- structure(list(year = c(2011L, 2011L, 2011L, 2011L, 2011L, 2011L,
2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L,
2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2012L,
2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L,
2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L,
2012L, 2012L, 2012L), count = c(187L, 199L, 560L, 1000L, 850L,
400L, 534L, 911L, 390L, 1008L, 1173L, 1222L, 810L, 950L, 752L,
1125L, 468L, 710L, 290L, 670L, 855L, 614L, 1300L, 950L, 670L,
888L, 490L, 557L, 741L, 700L, 954L, 378L, 512L, 780L, 951L, 398L,
1544L, 903L, 769L, 1399L, 1021L, 1235L, 1009L, 1222L, 255L)), .Names = c("year",
"count"), class = "data.frame", row.names = c(NA, -45L))
df阅读barplot
的文档,了解如何指定零空间:
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)
以下是ggplot2和主题的示例:
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")
或者,如果您真的希望它像multhist
中的绘图一样(这不容易解释):
对于叠加直方图,我更喜欢使用密度图。它们对眼睛更容易,尤其是如果你有更薄的箱子和更多的箱子。有了你的数据,你就会得到这个
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")
您是否知道可以更改ggplot2中的“图形样式”(使用主题
s)?@Roland感谢您的评论。我以前在ggplot2中遇到过主题问题,但也许是时候重新审视它们了!谢谢如果有人知道一种简单的方法来调整multhist中的情节,那就太好了。@Roland谢谢你的回答。对于这种柱状图,ggplot2似乎是一个很好的包。我也想用multhist来解决问题,但也许用那种类型的情节是不可能的@Emily在multhist
中添加了如何更改空格。太棒了,谢谢。花了很长时间查看条形图帮助,却找不到它!谢谢这个例子。我觉得它真的很有用!想知道“密度”(y轴)使用哪种单位?@Pgibas曲线是将每个数据点转换为正态分布,然后将它们相加的结果。如果你能找到一个简单的方法来解释它的单位,我也想知道它。。除息的
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))
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")