Home > database >  Return both a base plot and ggplot from function
Return both a base plot and ggplot from function

Time:10-28

I'm trying to make a function that produces a few plots for visual evaluation. I generally use ggplot for most purposes, but the base plot for models is helpful as well. When I try to assign the base plot, it produces the plot, but doesn't assign it to the variable, so when I try to return the plots (using list()) the base plot doesn't show up and returns the ggplot plus a [NULL]

Toy example

library(tidyverse)
my.fun = function(){
      mod.lm = lm(mpg ~ disp, data = mtcars)
      p1 = mtcars %>%
            ggplot(aes(x = disp, y = disp)) 
            geom_point()
      par(mfrow = c(2,2))
      p2 <- plot(mod.lm)
      list(p1, p2)
}
my.fun()

CodePudding user response:

Base plotting functions write directly to a plotting device, unlike ggplot2 functions, which produce an object that does the writing when you print it. It's possible to save a base plot (using the recordPlot() function), but it is already adapted to whatever output device it was using, and won't look as good if displayed (using replayPlot()) on a different device.

CodePudding user response:

I've never used base plot, but in a few attemps and coming across recordPlot(), as @user2554330 (beat me for 2 minutes) says, you can save both plots. Changing the order of plot() and ggplot() worked for me so first plot() is called and not overwritte ggplot() output. Also you can store the list in a variable and call the objects then.

library(tidyverse)
library(mtcars)
library(ggplot2)
my.fun = function(){
  mod.lm = lm(mpg ~ disp, data = mtcars)
  par(mfrow = c(2,2))
  plot(mod.lm)
  p1 <-  recordPlot() 
  p2 <-  mtcars %>%
    ggplot(aes(x = disp, y = disp)) 
    geom_point()
  list(p1, p2)
}
my.fun()
a <- my.fun()
  • Related