用两个分组变量绘制直方图
Draw histograms with two grouping variables
我正在尝试使用 ggplot2 为具有两个分组变量的数据绘制直方图,每个分组变量都有两个级别。我想将其中一个分组变量设置为 fill (和组),另一个设置为 facet.
我希望 y 轴显示相对于每个填充以及每个面的百分比。
我的第一个想法是总结数据并使用 geom_bar
,例如:
df <- tibble(
x=round(rnorm(1:1000)*5, 0),
fill=rep(c("a", "b"), 500),
facet=c(rep("x", 500), rep("y", 500))
)
df %>% group_by(fill, facet, x) %>% summarize(n=n()) %>% mutate(n=n/sum(n)) %>%
ggplot(aes(x=x, y=n, group=fill, fill=fill)) +
geom_bar(stat="identity", position="dodge2") +
facet_wrap(~ facet)
产生了这张图。
但是,由于在这种情况下更改 bin 大小有点麻烦,所以我想使用 geom_histogram
。
然后我发现了这个问题:
How to plot faceted histogram (not bar charts) with percents relative to each facet?
并想出了以下代码:
df %>% ggplot(aes(
x=x,
y=stat(count/tapply(count, list(fill, PANEL), sum)[fill, PANEL]),
group=fill,
fill=fill
)) + geom_histogram(binwidth=1, position="dodge2") + facet_wrap(~ facet)
但是我得到一个错误:Error in unit(x, default.units) : 'x' and 'units' must have length > 0
。
有什么好的方法可以解决这个问题吗?
预先感谢您的帮助!
在第三行将 [fill, PANEL]
更改为 [PANEL]
给了我预期的输出。
df %>% ggplot(aes(
x=x,
y=stat(count/tapply(count, list(fill, PANEL), sum)[PANEL]),
group=fill,
fill=fill
)) + geom_histogram(binwidth=1, position="dodge2") + facet_wrap(~ facet)
我正在尝试使用 ggplot2 为具有两个分组变量的数据绘制直方图,每个分组变量都有两个级别。我想将其中一个分组变量设置为 fill (和组),另一个设置为 facet.
我希望 y 轴显示相对于每个填充以及每个面的百分比。
我的第一个想法是总结数据并使用 geom_bar
,例如:
df <- tibble(
x=round(rnorm(1:1000)*5, 0),
fill=rep(c("a", "b"), 500),
facet=c(rep("x", 500), rep("y", 500))
)
df %>% group_by(fill, facet, x) %>% summarize(n=n()) %>% mutate(n=n/sum(n)) %>%
ggplot(aes(x=x, y=n, group=fill, fill=fill)) +
geom_bar(stat="identity", position="dodge2") +
facet_wrap(~ facet)
产生了这张图。
但是,由于在这种情况下更改 bin 大小有点麻烦,所以我想使用 geom_histogram
。
然后我发现了这个问题:
How to plot faceted histogram (not bar charts) with percents relative to each facet?
并想出了以下代码:
df %>% ggplot(aes(
x=x,
y=stat(count/tapply(count, list(fill, PANEL), sum)[fill, PANEL]),
group=fill,
fill=fill
)) + geom_histogram(binwidth=1, position="dodge2") + facet_wrap(~ facet)
但是我得到一个错误:Error in unit(x, default.units) : 'x' and 'units' must have length > 0
。
有什么好的方法可以解决这个问题吗?
预先感谢您的帮助!
在第三行将 [fill, PANEL]
更改为 [PANEL]
给了我预期的输出。
df %>% ggplot(aes(
x=x,
y=stat(count/tapply(count, list(fill, PANEL), sum)[PANEL]),
group=fill,
fill=fill
)) + geom_histogram(binwidth=1, position="dodge2") + facet_wrap(~ facet)