質問

I'm trying to plot a polynomial line to my data, however the plot results in multiple diagonal lines instead of one single curved line.

I've managed to correctly produce a polynomial using a fake dataset, but when I use this subset of my data (below) and attached code, I get multiple straight lines through the data. I have also tried fit2 = lm(y ~ I(x^2) + x) as a variant with no luck.

(I would attach an image of the output but this is my first post and reputation is thus <10)

Any help is greatly appreciated.

x<-c(102.397, 101.863, 101.22, 101.426, 100.718, 100.665, 100.616, 
100.844, 100.567, 100.864, 100.779, 101.002, 101.465, 102.291, 
101.711, 101.208, 101.252, 100.781, 100.631, 100.87, 100.552, 
100.762, 100.62, 101.044, 100.956, 101.3, 102.065, 101.581, 101.136, 
101.122, 100.773, 100.55, 100.897, 100.747, 100.738, 100.585, 
100.697, 100.487, 100.726, 100.706, 100.809, 101.208, 101.752, 
101.498, 101.153, 101.035, 101.076, 100.544, 100.779, 100.792, 
100.601, 100.454, 100.682, 100.687, 100.49, 100.552, 100.886, 
100.936, 101.288, 101.284, 101.115, 101.026, 101.08, 100.777, 
100.637, 100.846, 100.782, 100.492, 100.72, 100.73, 100.598, 
100.261, 100.366, 100.563, 100.841)



y<- c(14.32613169, 13.72501806, 21.95599022, 16.48122392, 31.82829181, 
49.09958776, 34.80769231, 29.69148033, 37.67365199, 12.75652985, 
19.48755851, 15.2639087, 11.97119712, 15.69222982, 14.40972222, 
20.2803527, 18.36173722, 32.52930568, 57.40697943, 33.18696557, 
43.16302735, 34.08973698, 26.78616511, 16.15409518, 21.05716748, 
15.06352087, 16.6404671, 18.29689298, 21.19666048, 15.7168413, 
25.05327966, 59.63324601, 26.08805031, 28.93116956, 49.86901643, 
49.25615364, 37.8384913, 47.14684757, 29.71848225, 20.51349921, 
17.08812261, 22.06913828, 13.41404358, 19.45597049, 20.21563342, 
20.82317899, 19.16648094, 54.67094703, 31.24128312, 35.30612245, 
52.52072597, 34.42824882, 29.47282163, 28.90414317, 43.49371889, 
21.28460091, 17.10587147, 21.67644184, 18.17082023, 16.62439474, 
22.60932244, 23.04822808, 18.02791803, 33.44095941, 50.23319083, 
28.65369341, 28.86940033, 32.6568959, 18.89804325, 14.54496931, 
14.80571684, 43.49477683, 24.98729029, 19.12702305, 14.72747497)

    plot(x,y)
    fit<-lm(y ~ poly(x, 2))
    lines(x, predict(fit), col = "red")
役に立ちましたか?

解決

If you absolutely want to use the generic plotting functions in R, I've figured out the problem. Your x-values aren't in order, and lines simply plots things in order. To fix it, you have to order your x values:

Y<-predict(fit)
df<-data.frame(x,Y)
df2<-df[order(df$x),]
plot(x,y)
lines(df2$x,df2$Y,col="red")

enter image description here

他のヒント

You can do this nicely with a package called ggplot2:

install.packages("ggplot2")
library(ggplot2)
df<-data.frame(x,y)
ggplot(df,aes(x,y))+
  geom_point()+geom_smooth(method = "lm", formula = y ~ poly(x, 2),colour="red")

enter image description here

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top