r - 在 R 中,绘制非线性曲线

标签 r plot lines

有几个接近的引用,但我的 lines() 产生了多条弧线,而不仅仅是一条非线性曲线。它看起来像一个吊床,上面有一堆不需要的线条。如何生成简单的非线性线?数据集以 Auto.csv 形式提供,位于 http://www-bcf.usc.edu/~gareth/ISL/data.html .

    library(ISLR)
    data(Auto)
    lm.fit1=lm(mpg~horsepower,data=Auto) #linear
    lm.fit2=lm(mpg~horsepower+I(horsepower^2),data=Auto) #add polynomial
    plot(Auto$horsepower,Auto$mpg,col=8,pch=1)
    abline(lm.fit1,col=2)       #linear fit
    lines(Auto$horsepower,predict(lm.fit2),col=4)  #attempt at nonlinear

最佳答案

lines 以数据发生的任何顺序绘制数据。因此,如果您不先按 x 值排序,您会得到一堆乱七八糟的线随着 x 值从一行来回跳到下一行。试试这个,例如:

plot(c(1,3,2,0), c(1,9,4,0), type="l", lwd=7)
lines(0:3, c(0,1,4,9), col='red', lwd=4)

要获得漂亮的曲线,请先按 horsepower 排序:

curve.dat = data.frame(x=Auto$horsepower, y=predict(lm.fit2))
curve.dat = curve.dat[order(curve.dat$x),]

lines(curve.dat, col=4)  

enter image description here

然而,如果您不按 horsepower 排序,您会得到以下结果:

enter image description here

关于r - 在 R 中,绘制非线性曲线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36274961/

相关文章:

linux - 在 gnuplot 组多图上设置标签

arrays - matlab中的连接点

android - 如何在 opengl 2.0 中的对象上绘制线框?

graphics - 如何在 LWJGL/OpenGL 中制作基本线段

sed - 单行删除特定字符出现次数超过 x 次的行

r - 在 SPSS、R 或 Excel 中按其他变量分组的向量之间的欧氏距离

r - 获取每行最频繁的值并说明关系

python - 什么是相当于 R 的 `with` 的 python/pandas?

r - 将 R 连接到 POP 电子邮件服务器 (Gmail)

ruby - 使用 Ruby 进行科学编程