你需要将属性映射到美学(aes语句中的颜色)以生成图例。
cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h, fill = "BAR"),colour="#333333")+
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +
geom_point(aes(y=b, colour="LINE1"),size=3) +
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +
geom_point(aes(y=c,colour="LINE2"),size=3) +
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols) + scale_fill_manual(name="Bar",values=cols) +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
![在此输入图片描述](https://istack.dev59.com/Ce7rP.webp)
我理解Roland的观点,但由于只涉及3个属性,并且叠加条形图和误差线会引起复杂性问题,因此保留数据的宽格式可能是合理的。您可以使用geom_pointrange来稍微减少复杂度。
如果要更改原始数据中误差线图例的背景颜色,请在绘图规范中添加+ theme(legend.key = element_rect(fill = "white",colour = "white"))
。通常需要对所有元素进行一致的映射才能合并不同的图例,但当前在我的情况下会产生黑色背景的瑕疵。我认为guide = guide_legend(fill = NULL,colour = NULL)
可以将图例的背景设为空值,但实际上却没有成功。也许这值得再提一个问题。
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) +
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) +
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols, guide = guide_legend(fill = NULL,colour = NULL)) +
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
要消除图例中的黑色背景,需要使用guide_legend
的override.aes
参数。这样可以让您指定图例的特定方面,以确保其正确性。
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) +
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) +
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols,
guide = guide_legend(override.aes=aes(fill=NA))) +
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
![在此输入图像描述](https://istack.dev59.com/OCQHw.webp)