If I have a data like below, I made a linear regression graph per location.
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)
and the graph looks like below.
Now in location C, it does not show the linearity. So I want to not show the regression line (or provide different color or dotted line, etc.,) in only location C.
Could you let me know how to change regression line type per group?
Always many thanks!!
You could do what you want by multiple stat_smooth()
with different data.
For instance, different color and linetype in location C.
You can use three stat_smooth()
s, if you want to change style of regression line by each group (i.e. 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'
Created on 2023-04-13 with reprex v2.0.2