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

4

2 回答 2

7

编辑:用 OPs 数据更新(并切换 x/y)

ggplot 非常适合这种类型的东西。假设您的数据位于df

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

在此处输入图像描述

在这种情况下,stat_smooth 默认为 loess 和 95% 的置信区间,但这可以分别使用methodlevel参数进行更改。

于 2014-02-15T23:52:34.677 回答
3

在问题中使用x和切换yloess

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

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

在此处输入图像描述

于 2014-02-15T23:54:47.730 回答