0

我想用 ggplot 创建一个堆积条形图,其中条形的高度取决于一个变量的值(选民投票率以 % 为单位),而条形图的堆栈单独加起来是另一个变量的 100%(投票份额以 % 为单位) . 因此,1990 年的选民投票率为 96.7,而栏应填满每一党的个人投票份额,加起来为 100%(占 96.7%)。我看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)

一团糟。

提前致谢!

4

1 回答 1

1

我使用dplyr管道来:

  • 为调整后的投票总数创建一个列,该列是各方份额和总投票率的乘积。
  • 摆脱零行,因此最终输出上不会出现零
  • 计算应显示投票总数的 y 值,方法是cumsum()按党派投票份额,按年份分组。我不得不使用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)

输出

ggplot2 输出

于 2018-04-25T16:38:20.207 回答