[英]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.