1
saving_ggplot <- function(name = 'default', plotname = last_plot()) {
  image_name = paste(name, ".png", sep="")
  ggsave(image_name, plot = plotname,
         scale = 1, 
         dpi = 300, limitsize = TRUE)
}

This is my function which saves a ggplot. However, I for the life of me cannot figure out how to take the name argument as a string.

for example if someone runes saving_ggplot(FILENAME, PLOTNAME)

it will just say no object FILENAME. In python I can just capture it and use it as str(), but using as.character or toString in R still doesn't work.


Error:

saving_ggplot(weightvsageTEST, weightvsageplot)
Error in paste(name, ".png", sep = "") : 
  object 'weightvsageTEST' not found

Successful call using ggsave:

ggsave('weightvsage.png', plot = last_plot(),
       scale = 1, 
       dpi = 300, limitsize = TRUE)
14
  • Can you include the actual code which tries to call saving_ggplot with FILENAME as a parameter? Commented May 26, 2018 at 14:42
  • Not 100% sure what you mean, included the error message for example. Commented May 26, 2018 at 14:43
  • Also added a successful one using ggsave Commented May 26, 2018 at 14:44
  • Perhaps you are missing the point of my question. Is weightvsageTEST even defined somewhere? Commented May 26, 2018 at 14:45
  • no that's the point, I'm trying to use the input argument as a string and I don't know how to do that. I want to take whatever the user types in, for example weightvsageTEST and convert that to a string for the filename that gets created. Commented May 26, 2018 at 14:46

1 Answer 1

2

You can use substitute():

saving_ggplot <- function(name, plotname) {
  image_name = paste0(substitute(name), ".png") # paste0 removes need for sep arg
  ggsave(image_name, plot = plotname,
         scale = 1, 
         dpi = 300, limitsize = TRUE)
}

saving_ggplot(foo, p) # saves foo.png

Alternately, if you want to stay within tidyverse quasiquotation syntax, use enexpr() instead:

enexpr(name) # instead of substitute(name)

Data:

N <- 100
df <- data.frame(x=rnorm(n=N), y=rnorm(n=N))
p <- ggplot(df, aes(x,y)) + geom_smooth()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.