[英]Using frequency on subgroups of ggplot/facet_wrap()
在繪制分類變量的小倍數時,我使用了以下代碼:
ggplot(raw, aes(x = income)) +
geom_bar(aes(y = ..count../sum(..count..), fill = factor(..x..))) +
facet_wrap("workclass")
然而,對於每個包裹,它給了我當前數據點在數據集總大小上的頻率,而不僅僅是在 facet_wrap 子集中。
我需要在此代碼中進行哪些更改,以便計數僅在 face_wrap 子集中運行?
您需要重新制定數據(即在調用ggplot()
之前按workclass
組組創建百分比數據)。 這是一個 data.table 方法來做到這一點。
require(data.table)
rawdt <- data.table(raw)
new_data <- rawdt[, .N, by = .(income, workclass)][, classN := sum(N), by = workclass][, y := N/classN]
ggplot(new_data, aes(x = income, y = y)) + geom_bar(stat = "identity") +
facet_wrap(~workclass)
你可以使用dplyr
例如,您在mtcars
數據集上的代碼:
ggplot(mtcars,aes(x = gear)) +
geom_bar(aes(y = ..count../sum(..count..), fill = factor(..x..))) +
facet_wrap("cyl")
像@amatsuo_net 的解決方案一樣重新整理數據,但使用dplyr
:
library(dplyr)
mtcars2 <- inner_join(mtcars %>%
group_by(cyl) %>%
summarise(total = n()),
mtcars %>%
group_by(gear,cyl) %>%
summarise(sub_total = n()),
by = "cyl") %>%
mutate(prop = sub_total/total)
ggplot(data = mtcars2, aes(x = gear,y=prop)) +
geom_bar(stat = "identity") +
facet_wrap(~cyl)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.