rplotbackground-coloreffect

How to change the plot background color generated by plot(effect(...)) in grey with white grid in R?


My R codes:

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

I tried to plot the main effect of green_text:

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
)

I tried to change the background of the plot into grey with white grid, so that it looked better. However, I kind of lost ways to achieve it. I have tried

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

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

To fix it, I tried

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)

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

but then the plot and the grey background were separated in two. I also saw a saying: {effects} plot is {lattice} based in r, so setting the par() won't have any effect. Does anyone know how to achieve this on the base of plot(effect(...))? Many thanks in advance.


Solution

  • This gets close. These are lattice plots, so you'll need to dig into the documentation of ?plot.effect and the lattice package documentation (?lattice::trellis.par.set) for fine tuning

    library(effects)
    lattice::trellis.par.set("panel.background", list(col = "gray"))
    m1 <- lm(mpg ~ hp, data = mtcars)
    e1 <- effect("hp", m1)
    plot(e1, axes = list(grid = TRUE))
    

    The OP suggests

    lattice::trellis.par.set(
        reference.line = list(col = "#FFFFFF", lwd=2),
        panel.background=list(col="#F6F6F6"))