2

My reproducible data is as follows:

x <- c(7232L, 6274L, 8163L, 7421L, 6362L, 7206L, 7600L, 7421L, 9381L, 
       8173L, 7473L, 6318L, 5360L, 4732L, 7249L, 6435L, 5556L, 6256L, 
       6543L, 6113L, 8288L, 7438L, 6272L)
y <- c(1.649, -0.27, 0.149, 0.504, -0.634, 1.067, -1.243, 0.539, -2.399, 
       0.281, 0.217, 0.371, -0.937, -2.238, -0.71, 0.295, -0.289, -0.271, 
       0.944, 0.724, -0.149, 0.204, 1.932)

Plotting this:

plot(y,x)

gives a simple scatter plot:

enter image description here

How do I add a curve of best fit to the above scatter plot? I came across abit of stuff on using the loess function, but that didn't seem to work.

I'm new to R and I've been searching for this for a couple hours nows. Any help would be GREATLY appreciated.

Thanks

Andy
  • 4,549
  • 31
  • 26
luks
  • 119
  • 1
  • 2
  • 7

2 Answers2

8

EDIT: updated with OPs data (and switching x/y)

ggplot is great for this type of stuff. Assuming your data is in df:

library(ggplot2)
qplot(y, x) + stat_smooth()

enter image description here

In this case stat_smooth defaults to loess and a 95% confidence intervals, but this could be changed with the method and level parameters, respectively.

BrodieG
  • 51,669
  • 9
  • 93
  • 146
3

Using x and y switched around as in the question and loess

dat <- dat[order(dat$y),]

fit <- loess(x ~ y, data = dat)
plot(dat$y, dat$x)
lines(dat$y, predict(fit, dat))

enter image description here

Jake Burkhead
  • 6,435
  • 2
  • 21
  • 32