0

I am making a function for easily save my plots. I wrote the function as follows:

Cases07 <- plot_usmap(data = data, values = "case2107_rate1000", regions = "county") +
  scale_fill_manual(values = cols, labels=label, na.value="grey", drop = FALSE)+
  labs(title ="Cases per 1000") + 
  guides(fill=guide_legend(title="Cases per 1000")) + thm

#Here is the plot saving function
savemap <- function(x){
  png(paste(deparse(substitute(x)),".png",sep = ""),width = 1200, height =900, units = "px")
  x
  dev.off()
}

However, this doesn't work.

savemap(Cases07). #This does not save my plot as expected.

But, either

savemap <- function(x){
  paste(deparse(substitute(x)),".png",sep = "")
}
#This outputs "Cases07.png".

or

savemap <- function(x){
  x
}
#This plots the map.

worked as expected.

The original function does not save my plot. Anyone knows why this happens?

Alex
  • 1
  • 1
    Can you provide any details about what occurs when you run your `savemap` function? Including a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample data will make it easier for people to help you. [This post](https://stackoverflow.com/questions/28867938/r-trouble-saving-plot-to-image-cannot-copy-from-the-null-device) may also help you. – Lief Esbenshade Jan 01 '21 at 08:14
  • Hi, thank you for your comments. I have find the problem and the solution to this. I posted solution below. – Alex Jan 02 '21 at 01:35

1 Answers1

0

just find the solution.

savemap <- function(x){
  png(paste(deparse(substitute(x)),".png",sep = ""),width = 1200, height =900, units = "px")
  plot(x)
  dev.off()
}

Use plot(x) works.

Alex
  • 1