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

时间:2022-02-20 13:06:00

My questions is similar to Normalizing y-axis in histograms in R ggplot to proportion but I'd like to add to it a bit.

我的问题类似于将R ggplot中的直方图中的y轴标准化为比例,但我想稍微添加一下。

In general, I have 6 histograms in a 2x3 facet design, and I'd like to normalize each of them separately. I'll try to make a sample data set here to give an idea:

一般来说,我在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)

Using

运用

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

gives the proportions overall (i.e. combining all the facets). I'd like each group facet to be normalized to 1. hvalues are not integers in my actual data - they are numerical.

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

I am a novice using R, and would really appreciate some help. Thanks in advance!

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

1 个解决方案

#1


7  

The solution is:

解决方案是:

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

I stole this from this question

我从这个问题中偷走了这个

I feel your question might be a duplicate of that one by the way.

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

#1


7  

The solution is:

解决方案是:

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

I stole this from this question

我从这个问题中偷走了这个

I feel your question might be a duplicate of that one by the way.

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