簡體   English   中英

R中的多個回歸線

[英]Multiple Regression lines in R

我正在嘗試使用回歸線輸出2個不同的圖形。 我正在使用mtcars數據集,我相信您可以將其加載到R中。因此,我正在比較2對不同的信息對以創建回歸線。 問題似乎是由於某種原因,第二張圖的第二條回歸線也在第一張圖中。

我只希望它在每張圖中以應有的方式顯示1條回歸線。

mtcars
names(mtcars)
attach(mtcars)    

par(mfrow=c(1,2), bg="white")
with(mtcars,
{

regrline=(lm(gear~mpg))
abline(regrline)
plot(mpg,gear,abline(regrline, col="red"),main="MPG vs Gear")

# The black line in the first graph is the regression line(blue) from the second graph

regrline=(lm(cyl~disp))
abline(regrline)
plot(disp,cyl,abline(regrline, col="blue"),main="Displacement vs Number of Cylinder")

})

另外,當我分別運行代碼進行繪圖時,看不到黑線。 只有當我使用:with()運行它時,它才會引起問題。

在此處輸入圖片說明

首先,您確實應該避免使用attach 對於具有data=參數的函數(例如plotlm ),通常明智的做法是使用該參數而不是with()

另外, abline()是應在plot()之后調用的函數。 將它作為plot()的參數並沒有任何意義。

這是您的代碼的更好安排

par(mfrow=c(1,2), bg="white")

regrline=lm(gear~mpg, mtcars)
plot(gear~mpg,mtcars,main="MPG vs Gear")
abline(regrline, col="red")

regrline=lm(cyl~disp, mtcars)
plot(cyl~disp,mtcars,main="Displacement vs Number of Cylinder")
abline(regrline, col="blue")

你明白我的第二回歸線,因為你調用abline()之前plot()的第二個回歸,做行吸取了第一條曲線。

這是您的代碼整理了一下。 您對多余的abline進行了多余的調用, abline繪制了多余的線條。

順便說一句,當with一起使用時,您不需要使用attach with基本上是一個暫時的attach

par(mfrow=c(1,2), bg="white")
with(mtcars,
{
    regrline=(lm(gear~mpg))
    plot(mpg,gear,main="MPG vs Gear")
    abline(regrline, col="red")

    regrline=(lm(cyl~disp))
    plot(disp,cyl,main="Displacement vs Number of Cylinder")
    abline(regrline, col="blue")
}
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM