I have a data like below and drew a quadratic graph.
nitrogen<- c(10,20,30,40,50,60)
yield<- c(15,25,38,42,35,30)
dataA<- data.frame(nitrogen,yield)
dataA
ggplot(data=dataA, aes(x=nitrogen, y=yield))+
stat_smooth(method='lm', linetype=1, se=FALSE, formula=y~poly(x,2, raw=TRUE), size=0.5, color="dark red") +
geom_point (col="Black", size=5) +
scale_y_continuous(breaks = seq(0,60,10), limits = c(0,60)) +
scale_x_continuous(breaks = seq(0,60,10), limits = c(0,60)) +
labs(x="Nitrogen", y="Yield") +
theme_classic(base_size=18, base_family="serif")+
theme_grey(base_size=15, base_family="serif")+
theme(axis.line= element_line(size=0.5, colour="black"))+
windows(width=5.5, height=5)
Now I'd like to draw a quadratic plateau graph like a right figure.
Could you let me know how to do it?
Many thanks!!
First, create the plot using stat_smooth. Then use ggplot_build to isolate the data points created by stat_smooth. Find the maximum and set y to equal the maximum once the maximum is hit. Then use your original data set for geom_point and the new data set for a line graph in ggplot.
myPlot <- ggplot(data=dataA, aes(x=nitrogen, y=yield))+
stat_smooth(method='lm', linetype=1, se=FALSE, formula=y~poly(x,2, raw=TRUE), size=0.5, color="dark red") +
scale_y_continuous(breaks = seq(0,60,10), limits = c(0,60)) +
scale_x_continuous(breaks = seq(0,60,10), limits = c(0,60))
smooth <- ggplot_build(myPlot)$data[[1]][c("x","y")]
smooth$y[which(smooth$y == max(smooth$y)):nrow(smooth)] <- max(smooth$y)
ggplot()+
geom_point(data=dataA, aes(x=nitrogen, y=yield),col="Black", size=5) +
geom_line(data = smooth, aes(x = x, y = y),color="dark red") +
scale_y_continuous(breaks = seq(0,60,10), limits = c(0,60)) +
scale_x_continuous(breaks = seq(0,60,10), limits = c(0,60)) +
labs(x="Nitrogen", y="Yield") +
theme_classic(base_size=18, base_family="serif")+
theme_grey(base_size=15, base_family="serif")+
theme(axis.line= element_line(size=0.5, colour="black"))