Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using ggplot to plot curvilinear fit

Tags:

r

ggplot2

How do I plot a curve for a line of best fit using ggplot? My best guess is that I need to change the stat_smooth parameter somehow but I have no clue how. My goal is something like the black line in the image below.enter image description here

vv<-structure(list(X = 16:19, school = structure(c(3L, 3L, 3L, 3L), .Label = c("UCB", "UCD", "UIUC"), class = "factor"), year = 2009:2012, mean = c(15.60965, 16.785, 16.77725, 15.91729), sd = c(6.483547,6.852999, 6.327013, 6.74991)), .Names = c("X", "school", "year", "mean", "sd"), row.names = 16:19, class = "data.frame")

ggplot(vv, aes(x = year, y = mean)) + 
  ggtitle("scores")+
  geom_point() +
  stat_smooth(method = "lm", col = "red")
like image 361
Rilcon42 Avatar asked Feb 27 '26 15:02

Rilcon42


1 Answers

You can try changing the formula:

ggplot(vv, aes(x = year, y = mean)) + 
  ggtitle("scores")+
  geom_point() +
  stat_smooth(method = "lm", formula = y ~ splines::bs(x, 3), col = "red")

enter image description here

like image 168
HubertL Avatar answered Mar 01 '26 04:03

HubertL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!