[英]Add custom labels to bars in ggplot stacked bar graph with multiple variables
[英]ggplot stacked bar graph with bars relating to two different variables with percentages
我想用ggplot创建一个堆叠的条形图,其中条形的高度取决于一个变量的值(选民投票率,以%为单位),条形图的堆栈分别加起来另一个变量的百分比为100%(选股,%) 。 因此,在1990年,选民的投票率为96.7,应该用每个党派的个人投票份额来填满选民,总数达到96.7%的100%。 我看了3方和3年的数据。
这是我的数据:
party <- c("a", "b", "c", "a", "b", "c", "a", "b", "c")
year <- c(1990, 1990, 1990, 1991, 1991, 1991, 1992,1992, 1992)
voteshare <- c(0,33.5, 66.5, 40.5, 39.0, 20.5, 33.6, 33.4, 33)
turnout = c(96.7,96.7,96.7, 85.05,85.05,85.05, 76.41, 76.41, 76.41)
df<- data.frame(parties, year, voteshare, turnout)
另外,我想将各个投票份额的数字和总投票数放在图表内。
到目前为止,我的方法:
ggplot(df, aes(x=year, y=interaction(turnout, voteshare), fill=party)) +
geom_bar(stat="identity", position=position_stack()) +
geom_text(aes(label=Voteshare), vjust=0.5)
一团糟。
在此先感谢一吨!
我使用dplyr
管道执行以下操作:
cumsum()
,计算应显示总投票数的y值。 我必须使用rev()
因为position_stack()
的默认值是将低位数字按字母顺序放在堆栈的顶部。 码
library(dplyr)
library(ggplot2)
df <- df %>%
mutate(adj_vote = turnout * voteshare / 100) %>%
filter(adj_vote > 0) %>%
group_by(year) %>%
mutate(cum_vote = cumsum(rev(adj_vote)),
vote_label = rev(voteshare))
ggplot(df, aes(x=year, y=adj_vote, fill=party)) +
geom_bar(stat="identity", position=position_stack()) +
geom_text(aes(label=vote_label, y = cum_vote), vjust=0.5)
产量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.