更改 R 中效果图的轴限制

Changing axis limits of effects plot in R

我正在使用效果包来绘制线性回归的交互效果,如下所示:

library(effects)
Model <- lm(drat~hp*cyl, data=mtcars)
plot(effect(term="hp*cyl",mod=Model,default.levels=10),multiline=TRUE)

如何更改限制,使它们从 0 变为 10?我试过 ylim=(0,10) 和其他没有效果的变体。或者,是否可以使用 ggplot2 以相同的方式绘制回归图?

plot函数,这样设置ylim

plot(effect(term="hp*cyl",mod=Model,default.levels=10),multiline=TRUE,ylim=c(0,10))

这里是 ggplot2 版本:

library(effects)
library(ggplot2)
Model <- lm(drat~hp*cyl, data=mtcars)
ef <- effect(term = "hp:cyl", Model, default.levels = 9) # 9 because the breaks are nicer
ef2 <- as.data.frame(ef)

ggplot(ef2, aes(hp, fit, col = factor(cyl))) +
  geom_line() +
  labs(y = 'drat') +
  ylim(0, 10)

ggplot2 不知道如何处理 class 'eff' 的数据,因此您需要在绘图之前将效果数据转换为数据帧。然后,您可以使用 group=aes() 中的数据来获取每个组的行。

library(effects)
library(ggplot2)
Model <- lm(drat~hp*cyl, data=mtcars)
e<-effect(term="hp*cyl",mod=Model,default.levels=10)
ee<-data.frame(e)
ee$cyl<-factor(ee$cyl)
ggplot(ee, aes(x = hp, y = fit, group = cyl, colour = cyl)) +
       geom_line() +
       scale_y_continuous(limits = c(0,10))