Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R ggplot2位置为“的加权条形图;道奇;_R_Ggplot2_Geom Bar - Fatal编程技术网

R ggplot2位置为“的加权条形图;道奇;

R ggplot2位置为“的加权条形图;道奇;,r,ggplot2,geom-bar,R,Ggplot2,Geom Bar,我正在尝试用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") 如何使钢筋长度与

我正在尝试用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")

如何使钢筋长度与总重量相匹配?

您可以先按所需方式总结数据,然后绘制:

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)

您可以先以所需的方式总结数据,然后绘制数据:

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)

@kath的解释是正确的

另一种选择是,如果您不想在将数据帧传递到
ggplot()
之前对其进行汇总:请使用
stat\u summary()
函数,而不是
geom\u bar()


@kath的解释是正确的

另一种选择是,如果您不想在将数据帧传递到
ggplot()
之前对其进行汇总:请使用
stat\u summary()
函数,而不是
geom\u bar()