stat_sum和stat_identity给出了奇怪的结果

时间:2015-01-15 14:10:07

标签: 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    

或者我做错了什么?

1 个答案:

答案 0 :(得分:7)

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