简体   繁体   中英

R: Create a User-defined Function that Plots data and then Exports the plot

Simple objective: I'm trying to create a user-defined fn ( udf ) that will allow me to combine a few lines of code so it's condensed and easier to read.

Let's take an easy example. In one fn, I'd like to plot some data and then export the plot using the tiff fn (or any similar fn: png , jpeg , ...). However, I want to be able to use any plot function of my choice , so I thought passing a code block (let's call it ' plotcode ') to a fn call would work just fine. Something along the lines of:

udf <- function(plotcode, title){
plotcode
tiff(filename=title)
   plotcode
   dev.off()
}

The ultimate goal being to turn 4 lines of code into 1, ie:

plot(dat)               # ====>     udf(plotcode = plot(dat),  title = "plot.tiff")
tiff("myplot.tiff")    
plot(dat)               
dev.off()

Unfortunately, it only plots the data and does not export it to a file. From what I understand, it's because I'm opening a graphics device when I use the export function, so it doesn't recognize the plotcode anymore?

I did find one alternative solution, the do.call fn, but it makes you separate the plotcode into two pieces: (1)fn name & (2)arguments. I'm hoping to keep the plotcode together so it's easer to copy/paste later.

Maybe there's even another option I'm not thinking of?

Following code lets you pass code that creates a plot, create the plot and save the plot.

library(tidyverse)

udf <- function(plotcode, title){
  eval(plotcode)
  ggsave(title)
}

udf('qplot(mtcars$mpg)', 'plot.jpg')

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