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

标签 r ggplot2

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

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/

相关文章:

r - 用 R 与单词字典进行字符串匹配

r - 如何确保 spatstat::owin(poly=<polygon>) 中的多边形没有 "negative area"

r - ggplot2:如何通过多个变量为图形着色

r - 如何将 cairo 设置为 R 中 x11() 的默认后端?

r - ggplot2:在右侧为一个变量创建第二个 y 轴

r - ggplot 柱形图 - brewer 对象中的颜色顺序无效

r - 绘制没有插值的 3D 表面?

r - 将数据框列中的列表转换为 R 中的单个列表

r - dplyr 无效的下标类型列表

r - 单行图例(错误 : Don't know how to add o to a plot)