You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中为plot(effect(...))设置灰色背景与白色网格

问题:如何为effects包绘制的主效应图设置灰色背景与白色网格?

我的代码尝试

我先拟合线性模型并提取主效应:

model0_1 <- lm(average_count ~ green_text + brand_names, data = data)
eff <- effect("green_text", model0_1)

接着尝试绘制主效应图:

plot(eff,
     x.var = "green_text",
     xlab = "Types of Tweets",
     ylab = "Average Count",
     main = "Types of Tweets on Average Count",
     colors = c("#1A9F12"),
     grid = TRUE
)

我想把图表背景改成灰色,搭配白色网格,尝试用base绘图的rect()函数:

rect(usr[1], usr[3], usr[2], usr[4], col = "lightgrey", border = NA)

但Jupyter Notebook返回错误:

Error in rect(usr[1], usr[3], usr[2], usr[4], col = "lightgrey", border = NA): plot.new has not been called yet

后来我调整代码,先绘图再调用plot.new(),但图表和灰色背景变成了两个独立图像:

plot(eff,
     x.var = "green_text",
     xlab = "Types of Tweets",
     ylab = "Average Count",
     main = "Types of Tweets on Average Count",
     colors = c("#1A9F12"),
     grid = TRUE)

plot.new() 
rect(usr[1], usr[3], usr[2], usr[4], col = "lightgrey", border = NA)

我知道effects包的绘图基于lattice,par()设置不生效,请问怎么在plot(effect(...))的基础上实现需求?

解决方案

因为effects的绘图依赖lattice系统,必须用lattice的主题配置来调整背景和网格样式,具体有两种方式:

方式1:在plot函数中直接指定par.settings参数

直接在plot.eff()调用里传入par.settings,一次性设置背景色和网格色:

model0_1 <- lm(average_count ~ green_text + brand_names, data = data)
eff <- effect("green_text", model0_1)

plot(eff,
     x.var = "green_text",
     xlab = "Types of Tweets",
     ylab = "Average Count",
     main = "Types of Tweets on Average Count",
     colors = c("#1A9F12"),
     grid = TRUE,
     par.settings = list(
       panel.background = list(col = "lightgrey"), # 设置面板背景为浅灰色
       grid.pars = list(col = "white") # 设置网格线为白色
     )
)

方式2:全局设置lattice主题

如果需要让后续所有lattice绘图都应用这个样式,可以先用trellis.par.set()全局配置:

# 全局设置lattice主题
trellis.par.set(
  panel.background = list(col = "lightgrey"),
  grid.pars = list(col = "white")
)

# 绘制效应图
model0_1 <- lm(average_count ~ green_text + brand_names, data = data)
eff <- effect("green_text", model0_1)

plot(eff,
     x.var = "green_text",
     xlab = "Types of Tweets",
     ylab = "Average Count",
     main = "Types of Tweets on Average Count",
     colors = c("#1A9F12"),
     grid = TRUE
)

关键说明

base绘图系统的rect()、par()等函数和lattice系统不兼容,所以之前的尝试会报错或生成独立图像。必须通过lattice的par.settings或trellis.par.set()来调整绘图外观。

内容的提问来源于stack exchange,提问作者Bella

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 01:07:36