如何用ggplot绘制lm()的残差?

时间:2016-04-19 23:09:57

标签: r ggplot2 lm

我想有一个很好的关于我从lm()模型得到的残差的情节。目前我使用plot(model$residuals),但我希望有更好的东西。如果我尝试使用ggplot绘制它,我会收到错误消息:

  

ggplot2不知道如何处理类数字

的数据

4 个答案:

答案 0 :(得分:21)

不再推荐Fortify,可能会根据Hadley弃用。

你可以使用扫帚包做类似的事情(更好):

library(broom)
y <-rnorm(10)
x <-1:10
mod <- lm(y ~ x)
df <- augment(mod)
ggplot(df, aes(x = .fitted, y = .resid)) + geom_point()

答案 1 :(得分:7)

df.stack(dropna=False).swaplevel(0,1).sort_index(level=0) Out[261]: 0 address 123 Fake Street email example@example.com item Apple notes None orderTime 14:55 paymentStatus COMPLETED refundNotes None transactionID 2132123 1 address 123 Example Street email fake@example.com item Banana notes None orderTime 15:10 paymentStatus REFUNDED refundNotes None transactionID 54654645 2 address 123 Top Secret email notreal@notreal.com item Orange notes None orderTime 23:11 paymentStatus COMPLETED refundNotes None transactionID 56754646 dtype: object 用于回归诊断图的ggfortify::autoplot()版本。请参阅此vignette

实施例

gg

enter image description here

答案 2 :(得分:2)

ggplot想要一个data.frame。 fortify会为你制作一个。

y <-rnorm(10)
x <-1:10
mod <- lm(y ~ x)
modf <- fortify(mod)
ggplot(modf, aes(x = .fitted, y = .resid)) + geom_point()

答案 3 :(得分:0)

现在,您可以使用为在CRAN上创建ggplot类型残差图而开发的ggResidpanel软件包。您可以找到入门教程here

相关问题