简体   繁体   中英

Customize checkresiduals() function in R with a `ggtheme` package

I am writing a report in RMarkdown. Using a classic theme_economist() for visualizations.

All my plots have the same style. For example

But there is one function, checkresiduals() , which is not a part of the tidyverse family and I cannot customize it with theme_economist() .

As a result, it is the only plot without a theme, which annoys a bit my perfectionism.

Any chance to customize it?

There are other ways to plot residuals with ggplot2() , but I like that function. Maybe somebody knows how to customize it? I appreciate your tips!

A REPRODUCIBLE EXAMPLE

# Packages
library(tidyverse)
library(forecast)
library(ggthemes)

# Data
data(mtcars)

# Create a plot
ggplot(mtcars, aes(disp, hp)) + 
   geom_point(color = "red", size = 3) + 
   labs(title = "I love mtcars",
        subtitle = "Do you love mtcars?",
        x = "disp",
        y = "hp") +
   theme_economist()

# Fit a model
mtcars_model <- lm(disp ~ hp, data = mtcars)

# Check residuals
checkresiduals(mtcars_model, color = "red")

Output

It doesn't look like that function makes it easy to customize the ggplots it returns, but since you are just setting a theme, you can set a global theme.

theme_set(theme_economist())

which will change the theme for all subsequent plots in your session. Alternatively you could write a wrapper to change the theme, draw the plot, then change it back. For example

with_theme_economist <- function(expr) {
  orig <- theme_get()
  theme_set(theme_economist())
  force(expr)
  theme_set(orig)
}

with_theme_economist(checkresiduals(mtcars_model, color = "red"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM