gpt4 book ai didi

r - stat_sum 和 stat_identity 给出奇怪的结果

转载 作者:行者123 更新时间:2023-12-04 18:05:56 25 4
gpt4 key购买 nike

我有以下代码,包括随机生成的演示数据:

n <- 10
group <- rep(1:4, n)
mass.means <- c(10, 20, 15, 30)
mass.sigma <- 4
score.means <- c(5, 5, 7, 4)
score.sigma <- 3
mass <- as.vector(model.matrix(~0+factor(group)) %*% mass.means) +
rnorm(n*4, 0, mass.sigma)
score <- as.vector(model.matrix(~0+factor(group)) %*% score.means) +
rnorm(n*4, 0, score.sigma)
data <- data.frame(id = 1:(n*4), group, mass, score)
head(data)

这使:
  id group      mass    score
1 1 1 12.643603 5.015746
2 2 2 21.458750 5.590619
3 3 3 15.757938 8.777318
4 4 4 32.658551 6.365853
5 5 1 6.636169 5.885747
6 6 2 13.467437 6.390785

然后我想在条形图中绘制按“组”分组的“分数”的总和:
plot <- ggplot(data = data, aes(x = group, y = score)) + 
geom_bar(stat="sum")
plot

这给了我:
enter image description here

奇怪的是,使用 stat_identity似乎给出了我正在寻找的结果:
plot <- ggplot(data = data, aes(x = group, y = score)) + 
geom_bar(stat="identity")
plot

enter image description here

这是一个错误吗?在 R 上使用 ggplot2 1.0.0
platform       x86_64-pc-linux-gnu         
arch x86_64
os linux-gnu
system x86_64, linux-gnu
status
major 3
minor 1.2
year 2014
month 10
day 31
svn rev 66913
language R
version.string R version 3.1.2 (2014-10-31)
nickname Pumpkin Helmet

或者我做错了什么?

最佳答案

plot <- ggplot(data = data, aes(x = group, y = score)) + 
stat_summary(fun.y = "sum", geom = "bar", position = "identity")
plot

resulting plot
aggregate(score ~ group, data=data, FUN=sum)
# group score
#1 1 51.71279
#2 2 58.94611
#3 3 67.52100
#4 4 39.24484

编辑:
stat_sum不起作用,因为它不只是返回总和。它返回“该位置的观察次数”和“该面板中该位置的点百分比”。它是为不同的目的而设计的。文档说“对于散点图的过度绘制很有用”。
stat_identity (有点)有效,因为 geom_bar默认情况下堆叠条形。与我的解决方案相比,您有许多条形堆叠,而我的解决方案每组只提供一个条形。看这个:
plot <- ggplot(data = data, aes(x = group, y = score)) + 
geom_bar(stat="identity", color = "red")
plot

还要考虑警告:
Warning message:
Stacking not well defined when ymin != 0

关于r - stat_sum 和 stat_identity 给出奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27965291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com