如果我有如下数据,我为每个位置制作了一个线性回归图。
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(width=8, height=7)
图表如下所示。
现在在C位置,没有表现出线性。所以我不想只在位置 C 显示回归线(或提供不同的颜色或虚线等)。
你能告诉我如何改变每组的回归线类型吗?
总是非常感谢!
你可以用不同的数据做你想做的事
stat_smooth()
。你可以使用三个
stat_smooth()
s,如果你想改变每组回归线的风格(即A,B,C)。
library(ggplot2)
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))+
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) +
stat_smooth(data=dataA[dataA$location!="C",], method="lm", se=F)+
stat_smooth(data=dataA[dataA$location=="C",], method="lm", se=F, lty=2, color="red",
formula = y ~poly(x,2)) +
theme_grey(base_size=20, base_family="serif")+
theme(axis.line=element_line(linewidth=0.5, colour="black"))
#> `geom_smooth()` using formula = 'y ~ x'
创建于 2023-04-13 与 reprex v2.0.2