如何在R中使用facet_wrap()按分组修改回归线类型?
按分组修改ggplot回归线样式(隐藏或调整特定分组)
先还原你的数据集与初始绘图代码:
location=rep(c("A","B","C"),each=5) nitrogen=rep(c(0,10,20,30,40), time=3) yield=c(15,20,25,29,38,10,20,40,50,55,15,17,16,17,20) dataA=data.frame(location, nitrogen, yield) ggplot(data=dataA, aes(x=nitrogen, y=yield))+ stat_smooth(method='lm', linetype=1, se=FALSE, formula=y~x, linewidth=0.5) + geom_point(color="black", size=4) + scale_x_continuous(breaks=seq(0,40,10), limits = c(0,40)) + scale_y_continuous(breaks=seq(0,60,10), limits = c(0,60)) + labs(x="N rate", y="Grain Yield") + facet_wrap(~location) + theme_grey(base_size=20, base_family="serif")+ theme(axis.line=element_line(linewidth=0.5, colour="black")) # 注:windows()是RStudio专属窗口设置,可根据环境调整
针对Location C无线性特征的需求,提供两种实现方式:
方式一:仅隐藏Location C的回归线
直接给stat_smooth指定过滤后的数据集,只对A、B分组绘制回归线:
ggplot(data=dataA, aes(x=nitrogen, y=yield))+ # 只给location不等于C的数据画回归线 stat_smooth(data = subset(dataA, location != "C"), method='lm', linetype=1, se=FALSE, formula=y~x, linewidth=0.5) + geom_point(color="black", size=4) + scale_x_continuous(breaks=seq(0,40,10), limits = c(0,40)) + scale_y_continuous(breaks=seq(0,60,10), limits = c(0,60)) + labs(x="N rate", y="Grain Yield") + facet_wrap(~location) + theme_grey(base_size=20, base_family="serif")+ theme(axis.line=element_line(linewidth=0.5, colour="black"))
方式二:自定义不同分组的回归线样式
如果不想完全隐藏,而是给C设置区别于A、B的样式(比如虚线、浅灰色),可以将样式属性与location绑定,再通过手动刻度设置自定义规则:
ggplot(data=dataA, aes(x=nitrogen, y=yield))+ # 将线型、颜色与location绑定 stat_smooth(aes(linetype=location, color=location), method='lm', se=FALSE, formula=y~x, linewidth=0.5) + geom_point(color="black", size=4) + scale_x_continuous(breaks=seq(0,40,10), limits = c(0,40)) + scale_y_continuous(breaks=seq(0,60,10), limits = c(0,60)) + # 手动设置每个location的线型:A、B用实线(1),C用虚线(2);若要隐藏则设为0 scale_linetype_manual(values = c("A"=1, "B"=1, "C"=2)) + # 手动设置颜色:A、B用黑色,C用灰色 scale_color_manual(values = c("A"="black", "B"="black", "C"="grey50")) + labs(x="N rate", y="Grain Yield") + facet_wrap(~location) + theme_grey(base_size=20, base_family="serif")+ theme(axis.line=element_line(linewidth=0.5, colour="black"))
如果需要完全隐藏C的回归线,只需把scale_linetype_manual中C的取值改为0即可(linetype=0表示无线条)。
内容的提问来源于stack exchange,提问作者J.K Kim
相关产品推荐
相关产品推荐

