geom_boxplotgeom_textgeom_hline 同时使用时,我不明白 ggplot 如何回复颜色列表或用户设置的线型 .

我想使用具有两个级别(例如白色和灰色)的分组因子来设置我的箱图的填充颜色,使用具有四个级别(例如,红色,橙色,蓝色,绿色)的分组因子来设置标签的文本颜色,以及添加三条水平线(两条参考值和具有定量变量的全局平均值的线) .

我已尝试使用 scale_color_manualscale_fill_manual 但没有令人满意的结果:我得到错误: insufficient values in manual scale ,指定的hlines没有显示,或者它们看起来与我想要的不同 .

以下示例脚本显示了我的问题:1)线要素错误(平均值应为实心和蓝色),2)箱线图的边框颜色不是黑色,3)图例与显示的要素不一致 .

group<-c(rep("a",8),rep("b",8))
subgroup<-c(rep("m1",4),rep("m2",4),rep("m1",4),rep("m2",4))
subgroup2<-c(rep(c("A","B","C","D"),4))
id<-c(rep(c("q","w","e","r"),2),rep(c("t","y","u","i"),2))
value<-c(0.5,1.5,2.5,3.5,1.8,2.8,3.8,4.8,2.7,3.7,4.7,5.7,4.5,5.5,6.5,7.5)
df<-data.frame(group,subgroup,subgroup2,id,value)

ggplot(df,aes(group,value))+
  geom_boxplot(aes(fill=subgroup, colour=subgroup))+
  theme_light()+
  theme(legend.position="bottom")+
  geom_text(data=subset(df, subgroup=="m1"), aes(label=id, color=subgroup2), size=3, position = position_nudge(x = -0.19)) +
  geom_text(data=subset(df, subgroup=="m2"), aes(label=id, color=subgroup2), size=3, position = position_nudge(x = 0.19)) + 
  stat_summary(data=subset(df, subgroup=="m1"),fun.y=mean, geom="point", shape=10, size=2,position = position_nudge(x = -0.19)) +
  stat_summary(data=subset(df, subgroup=="m2"),fun.y=mean, geom="point", shape=10, size=2,position = position_nudge(x = 0.19)) +
  geom_hline(aes(yintercept = 2.3, colour="green", linetype="dashed")) +
  geom_hline(aes(yintercept = 4.7, colour="red", linetype="dotted")) + 
  geom_hline(aes(yintercept = mean(value), colour="blue", linetype="solid"))

Figura Script