使用ggplot2中的stat_summary计算均值和sd,然后连接误差线的平均点

时间:2014-01-20 16:38:49

标签: r plot ggplot2

在以下示例中,根据原始数据计算平均值和se,并以条形图绘制。我想做同样的事情,但不是使用barplot我想使用连接点。所以,如果有人能告诉我如何,我将非常感激...谢谢

示例:

     data(ToothGrowth)

     ToothGrowth$F3 <- letters[1:2]
     # coerce dose to a factor
     ToothGrowth$dose <- factor(ToothGrowth$dose, levels = c(0.5,1,2))
     # facetting on the third factor
     ggplot(ToothGrowth, aes(y = len, x = supp )) + 
     stat_summary(fun.y = 'mean', fun.ymin = function(x) 0, geom = 'bar', 
     aes(fill =dose), position = 'dodge') +
     stat_summary(fun.ymin = function(x) mean(x) - sd(x), 
           fun.ymax = function(x) mean(x) + sd(x), position ='dodge', 
           geom = 'errorbar', aes(group = dose))+
    facet_wrap(~F3)   

1 个答案:

答案 0 :(得分:19)

您可以将geom pointrange用于指示平均值和错误栏的两个点。

ggplot(ToothGrowth, aes(y = len, x = supp, colour = dose, group = dose)) + 
  stat_summary(fun.y = mean,
               fun.ymin = function(x) mean(x) - sd(x), 
               fun.ymax = function(x) mean(x) + sd(x), 
               geom = "pointrange") +
  stat_summary(fun.y = mean,
               geom = "line") +
  facet_wrap( ~ F3)

enter image description here