简体   繁体   English

ggplot2位置为“ dodge”的加权条形图

[英]ggplot2 weighted bar plot with position = “dodge”

I am trying to make a weighted dodged bar plot with ggplot2. 我正在尝试使用ggplot2进行加权的加权条形图。 With stacked bars the behavior is as expected: 使用堆叠的钢筋,行为符合预期:

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")

The bars have length equal to the total weight. 条的长度等于总重量。

If I add position = "dodge", the length of the female group a bar is 4 rather than the expected 6. Similarly, all other bars are only as long as the highest weight in each group & sex combination rather than representing the total weight. 如果我添加position =“ dodge”,则女性组的一根杠的长度为4,而不是预期的6。类似地,所有其他杠的长度仅等于每个组和性别组合中最高的重量,而不代表总重量。

ggplot(df, aes(x = group, fill = sex, y = weight)) +
    geom_bar(stat = "identity", position = "dodge")

How do I make the bar lengths match the total weight? 如何使棒的长度与总重量匹配?

@kath's explanation is correct. @kath的解释是正确的。

Another alternative, if you don't want to summarise the data frame before passing it to ggplot() : use the stat_summary() function instead of geom_bar() : 另一种选择是,如果您不想在将数据帧传递给ggplot()之前对其进行ggplot()使用stat_summary()函数而不是geom_bar()

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

情节

You can first summarise the data in your desired way and then plot it: 您可以首先以所需的方式汇总数据,然后将其绘制:

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")

在此处输入图片说明

The problem with your original approach is that as you have several values of weight for one group, sex combination and then specify stat="identity" , they are plotted on top of each other. 原始方法的问题在于,由于一组有多个权重值,性别组合,然后指定stat="identity" ,因此它们会相互绘制。 This can be visualized: 可以看到:

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