我想为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")
以上是代码的样子(不包括颜色等)。
有人可以帮忙吗?为这个简单的问题提前道歉。干杯!
答案 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。