在ggplot2中分别标准化分面直方图

时间:2013-05-02 13:24:55

标签: r ggplot2 normalization histogram facet

我的问题类似于 Normalizing y-axis in histograms in R ggplot to proportion 但我想补充一点。

一般来说,我在2x3小平面设计中有6个直方图,我想分别对它们进行标准化。我将尝试在此处制作一个示例数据集以提供一个想法:

hvalues=c(3,1,3,2,2,5,1,1,12,1,4,3)
season=c("fall","fall","fall","fall","winter","winter","winter","winter","summer","summer","summer","summer")
year=c("year 1","year 1","year 2","year 2","year 1","year 1","year 2","year 2","year 1","year 1","year 2","year 2")
group=c("fall year 1","fall year 1","fall year 2","fall year 2","winter year 1","winter year 1","winter year 2","winter year 2","summer year 1","summer year 1","summer year 2","summer year 2")
all=data.frame(hvalues,season,year)

使用

ggplot(all, aes(x=hvalues,group=group)) + 
geom_histogram(aes(y=..count../sum(..count..))) + 
facet_grid(season ~ year)

给出整体比例(即组合所有方面)。我希望每个组的方面都被标准化为1.在我的实际数据中,hvalues不是整数 - 它们是数字的。

我是使用R的新手,非常感谢一些帮助。提前谢谢!

1 个答案:

答案 0 :(得分:9)

解决方案是:

ggplot(all, aes(x=hvalues)) +
    facet_grid(season ~ year,drop=T) +
    geom_histogram(aes(y=(..count..)/tapply(..count..,..PANEL..,sum)[..PANEL..]))

我从这个question

中偷走了这个

顺便说一句,我觉得你的问题可能与那个问题重复。