Rilcon42 Rilcon42 - 16 days ago 7
R Question

using ggplot to plot curvilinear fit

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")

Answer

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

Comments