如何在R geom_violin图中绘制误差线

时间:2018-09-03 12:16:22

标签: r ggplot2 violin-plot

我在某个地方犯了一个非常简单的错误。感谢您指出发生此错误的地方...

我想创建一个覆盖置信区间和组均值的小提琴图。非常类似于this的新包装中的示例。

没有任何CI的通用小提琴情节很好:

p <- ggplot(data=diamonds, aes(x=cut, y=price))
p + geom_violin(aes(x=cut, y=price)) +
  geom_jitter(height = 0, width = 0.1, alpha = 0.05) +
  geom_crossbar(stat="summary", fun.y=mean, fun.ymax=mean, fun.ymin=mean, 
                fatten=2, width=.5)

我的问题是纳入置信区间。

我首先创建必要的摘要统计信息:

errbar_lims <- group_by(diamonds, cut) %>% 
  summarize(mean=mean(price), se=sd(price)/sqrt(n()),             
  upper=mean+(2*se), lower=mean-(2*se))

然后我想用geom_errorbar添加到情节中:

p <- ggplot(data=diamonds, aes(x=cut, y=price))
p + geom_violin(aes(x=cut, y=price)) +
  geom_jitter(height = 0, width = 0.1, alpha = 0.05) +
  geom_crossbar(stat="summary", fun.y=mean, fun.ymax=mean, fun.ymin=mean, 
                fatten=2, width=.5) +
  geom_errorbar(aes(x= ymax=errbar_lims$upper, ymin=errbar_lims$lower), 
                stat='identity', width=.25)

但是ggplot的错误不断告诉我,我正在映射到单个组美学而不是我要绘制的5个组。

也许我的错误是我一开始如何设置映射?


更新

最初发布后查看了一些评论后,完整脚本现在如下所示:

errbar_lims <- group_by(diamonds, cut) %>% 
  summarize(mean=mean(price), se=sd(price)/sqrt(n()), 
        upper=mean+(2*se), lower=mean-(2*se))

p <- ggplot(data=diamonds, aes(x=cut, y=price))
p + geom_violin(aes(x=cut, y=price)) +    
  geom_jitter(height = 0, width = 0.1, alpha = 0.05) +
  geom_crossbar(stat="summary", fun.y=mean, fun.ymax=mean, fun.ymin=mean, 
            fatten=2, width=.5) +
  geom_errorbar(aes(x = cut, ymin = lower, ymax = upper), errbar_lims, inherit = FALSE)

但错误仍然存​​在:

Error in FUN(X[[i]], ...) : object 'price' not found

1 个答案:

答案 0 :(得分:1)

在github上您也指出了我的那段神话般的代码。

library(ggplot2)
View(ggplot2::diamonds)

ggstatsplot::ggbetweenstats(data = ggplot2::diamonds, x=cut, y=price, messages=FALSE)