簡體   English   中英

ggplot2位置為“ dodge”的加權條形圖

[英]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")

如何使棒的長度與總重量匹配?

@kath的解釋是正確的。

另一種選擇是,如果您不想在將數據幀傳遞給ggplot()之前對其進行ggplot()使用stat_summary()函數而不是geom_bar()

ggplot(df, aes(x = group, fill = sex, y = weight)) +
  stat_summary(geom = "bar", position = "dodge", fun.y = sum)

情節

您可以首先以所需的方式匯總數據,然后將其繪制:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM