[英]ggplot2 weighted bar plot with position = “dodge”
我正在嘗試使用ggplot2進行加權的加權條形圖。 使用堆疊的鋼筋,行為符合預期:
df <- data.frame(group = rep(letters[1:3], each = 4),
sex = rep(c("m", "f"), times = 6),
weight = 1:12)
ggplot(df, aes(x = group, fill = sex, y = weight)) +
geom_bar(stat = "identity")
條的長度等於總重量。
如果我添加position =“ dodge”,則女性組的一根杠的長度為4,而不是預期的6。類似地,所有其他杠的長度僅等於每個組和性別組合中最高的重量,而不代表總重量。
ggplot(df, aes(x = group, fill = sex, y = weight)) +
geom_bar(stat = "identity", position = "dodge")
如何使棒的長度與總重量匹配?
您可以首先以所需的方式匯總數據,然后將其繪制:
library(dplyr)
library(ggplot2)
df %>%
group_by(group, sex) %>%
summarise(total_weight = sum(weight)) %>%
ggplot(aes(x = group, fill = sex, y = total_weight)) +
geom_bar(stat = "identity", position = "dodge")
原始方法的問題在於,由於一組有多個權重值,性別組合,然后指定stat="identity"
,因此它們會相互繪制。 可以看到:
ggplot(df, aes(x = group, fill = sex, y = weight)) +
geom_bar(stat = "identity", position = "dodge", color = "black", alpha = 0.5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.