[英]How to plot the share of a variable in a histogram with ggplot2
我试过查看旧线程没有成功。 我正在尝试 plot 直方图中不同议会会议中男性立法者的份额。
这是我的代码,它有效,但显示了立法者的数量(不是份额)。 我怎样才能 plot 共享? 谢谢!
mergedf %>%
ggplot( aes(x = session, fill = factor(sex))) +
geom_histogram (binwidth = 0.5)+
theme_minimal()+
theme(legend.position ="bottom")+
labs(title = "Share of male legislators by session", x= "Session", y = "Share of legislators",
fill ="sex")
编辑:我通过这张表获得了立法者的份额,但我不知道如何将它整合到直方图中。
mergedf %>%
tabyl (session, sex) %>%
adorn_percentages() %>%
adorn_pct_formatting ()
一种选择是使用一些dplyr
动词来计算计数和百分比,然后可以通过geom_col
显示为条形图(直方图是不同的),如下所示:
mergedf <- data.frame(
sessions = c( 1, 2, 3, 4, 5, 2, 3, 4, 2),
sex = c ("female", "female", "female", "male", "female", "female", "female", "male", "male")
)
library(dplyr)
library(ggplot2)
mergedf %>%
group_by(sessions, sex) %>%
summarise(n = n()) %>%
mutate(pct = n / sum(n)) %>%
ggplot( aes(x = factor(sessions), y = pct, fill = sex)) +
geom_col(width = .6)+
theme_minimal()+
theme(legend.position ="bottom")+
labs(title = "Share of male legislators by session", x= "Session", y = "Share of legislators",
fill ="sex")
#> `summarise()` has grouped output by 'sessions'. You can override using the
#> `.groups` argument.
您只需在geom_histogram
参数中指定position="fill"
:
library(ggplot2)
mergedf <- data.frame(
session = c( 1, 2, 3, 4, 5, 2, 3, 4, 2),
sex = c ("female", "female", "female", "male", "female", "female", "female", "male", "male")
)
ggplot(mergedf, aes(x = session, fill = factor(sex))) +
geom_histogram (binwidth = 0.5, position = "fill") + # <- HERE
theme_minimal() +
theme(legend.position ="bottom") +
labs(title = "Share of male legislators by session",
x= "Session", y = "Share of legislators", fill ="sex")
从技术上讲,您并没有真正构建直方图(计数的合并分布),而是条形图,因此您也可以使用geom_bar
,格式相同:
ggplot(mergedf, aes(x = session, fill = factor(sex))) +
geom_bar(position="fill") +
theme_minimal () +
theme(legend.position ="bottom") +
labs(title = "Share of male legislators by session",
x= "Session", y = "Share of legislators", fill ="sex")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.