在ggplot中将平均线添加到双因子箱图中

时间:2018-04-17 16:30:24

标签: r ggplot2 boxplot

我想为6组中的每一组添加一条平均线,但是ggplot会添加一组平均线。情节目前如下所示:box plot

ggplot(test, aes(Factor1, YVar)) + geom_boxplot(aes(colour=Factor2)) + 
  labs(x="Factor 1", y="Y Var") +
  guides(color=guide_legend("Factor 2"))+
  stat_summary(fun.y=mean, geom="errorbar", aes(ymax=..y..,ymin=..y..), 
               width=0.75, linetype="dashed", size=1, color="black")

以上是代码的样子(不包括颜色等)。

有人可以帮忙吗?为这个简单的问题提前道歉。干杯!

1 个答案:

答案 0 :(得分:0)

只需在Factor2的电话中添加group作为stat_summary美学 - 这是一个更可重复的示例:

library(ggplot2)

# Original boxplot
ggplot(mtcars, aes(factor(cyl), mpg)) +
  geom_boxplot(aes(color = factor(am)))

# With dashed mean line
ggplot(mtcars, aes(factor(cyl), mpg)) +
  geom_boxplot(aes(color = factor(am))) +
  stat_summary(fun.y = mean, geom = "errorbar", 
               aes(ymax = ..y.., ymin = ..y.., group = factor(am)),
               width = 0.75, linetype = "dashed")

# Use position = position_dodge()
ggplot(mtcars, aes(factor(cyl), mpg)) +
  geom_boxplot(aes(color = factor(am))) +
  stat_summary(fun.y = mean, geom = "errorbar", 
               aes(ymax = ..y.., ymin = ..y.., group = factor(am)),
               width = 0.75, linetype = "dashed", position = position_dodge())

reprex package(v0.2.0)创建于2018-04-17。