r
  • plot
  • ggplot2
  • regression
  • scatter-plot
  • 2016-04-14 117 views 0 likes 
    0

    使用包ggplot2和iris,我想用擬合迴歸線繪製散點圖。如何在一張圖中繪製lm(log(y)〜)和lm(y〜x + x^2)的ggplot

    library(ggplot2) 
    ggplot(data=iris, aes(x = Petal.Width, y = Petal.Length,color=Species)) + 
        geom_point(shape=1) + 
        stat_smooth(method = "lm",formula= 'Petal.Length ~ Petal.Width+I(Petal.Width^2)+SaleType+Petal.Width*Species', data=iris, 
           aes(x = Petal.Width, y = Petal.Length,color=Species)) 
    
    **Warning message: 
    Computation failed in `stat_smooth()`: 
    variable lengths differ (found for '(weights)')** 
    

    我想到的理由得到這個警告,我有兩個獨立的變量,但現在R可以不讀物種在stat_smooth劈裂增長的顏色。我如何繪製兩條與plot(Petal.Width,fitted(fit))相同的線。另外,如果我有另一個迴歸模型擬合相同的數據組,但是log(y),我可以將兩個迴歸模型的繪製放入同一個圖中嗎?

    回答

    1

    我不認爲將變換後的迴歸與原始值在同一比例上結合是合適的。相反,這些應該繪製在不同的數字上。使用iris數據集,你可以畫出了這樣的原始數據:

    ggplot(data=iris, aes(color=Species)) + 
        geom_point(aes(x = Petal.Width, y = Sepal.Width)) + 
        stat_smooth(method = "lm", aes(x = Petal.Width, y = Sepal.Width,color=Species)) 
    

    然後登錄變換Sepal.Width到另一個變量:

    iris$LogSepal.Width <- log(iris$Sepal.Width) 
    

    然後劇情有轉換變量。我希望這有幫助。

    ggplot(data=iris, aes(color=Species)) + 
        geom_point(aes(x = Petal.Width, y = LogSepal.Width)) + 
        stat_smooth(method = "lm", aes(x = Petal.Width, y = LogSepal.Width,color=Species)) 
    
    +0

    謝謝!我有你的想法做日誌。但是,我怎樣才能繪製二次變量的迴歸擬合線和交互。 –

    +0

    我明白了。通常,在ggplot2之外運行模型(如果它們有任何複雜性)會更好。所以我會像正常一樣運行它,然後繪製模型結果。 – boshek

    相關問題