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