Home > OS >  How to plot smooth line through four points in R
How to plot smooth line through four points in R

Time:11-05

I have a data frame include two groups, each group with four points, and I want to plot them using smooth line in r. The dataframe is:

df <- data.frame(x=c(12,25,50,85,12,25,50,85), y=c(1.02, 1.05, 0.99, 1.07, 1.03, 1.06, 1.09, 1.10), Type=c("AD","AD","AD","AD","WT","WT","WT","WT"))

I used the code:

ggplot(df)   
geom_point(aes(x=x, y=y, color=Type, group=Type), size = 3)   
geom_line(aes(y=y, x=x, group = Type, color=Type))   
stat_smooth(aes(y=y, x=x), method = "loose", formula = y~ poly(x, 21), se = FALSE)

However the plot I got is not smooth as I expected. How could I change on code? Is it because the limited point number? Thanks a lot in advance! enter image description here

CodePudding user response:

There are a couple of problems with your code. Firstly, there is no method called "loose" for regression (did you mis-spell "loess"?). Secondly, if you want a polynomial regression you probably want method = lm. Thirdly, if you have four points in each series, you can have at most a degree-3 polynomial.

Using lm with y ~ poly(x, 3) works quite well here:

ggplot(df, aes(x, y, color = Type))  
  geom_point(size = 3)   
  stat_smooth(method = lm, formula = y ~ poly(x, 3), se = FALSE)

enter image description here

Or even just a loess with y ~ x

ggplot(df, aes(x=x, y=y, color=Type))  
  geom_point(size = 3)   
  stat_smooth(method = loess, formula = y ~ x, se = FALSE)

enter image description here

CodePudding user response:

Posting an alternative way of doing it.

  geom_point(size = 3)   
  geom_smooth(method = "loess", span = 0.75, se = FALSE)

You can the span-parameter. See some examples below:

span == 1:

enter image description here

span == 0.75:

enter image description here

  • Related