2017-06-14 50 views
0

我遇到了適合R的Loess問題。我使用每個R安裝中包含的默認虹膜數據集。但是,當我嘗試製作黃土線時,它會遍佈各處。黃土(y〜x)的黃土線是紅色的,因爲我想試驗一下,看看我是不是在排序x和y錯誤,黃土(x〜y)的線是藍色的。正如你所看到的,這些行很明顯是錯誤的。這是爲什麼發生?我似乎無法修復它。下面是代碼:黃土適合錯誤R,線路遍佈各地?

#ignore 
library(lattice) 
#cloud() 

#CODE OF CONCERN BELOW 
data <- iris 
n<-150 
x <- data$Petal.Length 
y<-data$Petal.Width 
plot(y ~ x) 
loess_fit <- loess(y~x) 
lines(x, predict(loess_fit), col = "blue") 

這裏是我得到的圖片:

enter image description here

+0

您需要先訂購點。 x < - sort(data $ Petal.Length); y <-data $ Petal.Width [order(data $ Petal.Length)] – G5W

+0

...或者命令行函數調用變量。 'line(x [order(x)],predict(loess_fit)[order(x)],col =「blue」)' – user20650

+2

[在R中使用LOESS適合行](https://stackoverflow.com/questions/15337777/fit-a-line-with-loess-in-r)相關https://stackoverflow.com/questions/10007830/loess-line-not-plotting-correctly – user20650

回答

1

您需要使用之前黃土訂購點。

x <- sort(data$Petal.Length) 
y<-data$Petal.Width[order(data$Petal.Length)] 
plot(y ~ x) 
loess_fit <- loess(y~x) 
lines(x, predict(loess_fit), col = "blue") 

loess curve