将曲线添加到R中的散点图

时间:2014-02-15 23:35:50

标签: r plot curve best-fit-curve

我的可重复数据如下:

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)

绘制图:

plot(y,x)

给出了一个简单的散点图:

enter image description here

如何在上面的散点图中添加最适合的曲线?我在使用loess函数时遇到了很多东西,但这似乎不起作用。

我是R的新手,我一直在寻找这个问题几个小时。任何帮助都会非常感激。

由于

2 个答案:

答案 0 :(得分:7)

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

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

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

enter image description here

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

答案 1 :(得分:3)

使用xy切换问题和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

相关问题