Return ggplot2 figure from sourced function

by Manuel Pasieka   Last Updated December 29, 2017 15:26 PM

i am struggling with R's print behavior when sourcing a function. I want to write a function that generates a ggplot and returns that plot in order to save it later.

So it should look something like this

file: func.R

make_plot <- function(data){
p <- ggplot(...)
print(p)
return(p)
}


source('func.R')
p <- make_plot(data)
ggsave('somewhere.png', plot=p)

my problem is that the generated plots are empty, and calling print(p) outside of the function generates a empty plot as well.

If I run the code inside of the function interactively, everything is fine.

Any ideas?

Tags : r ggplot2


Answers 1


thank you for your quick responses. I am very sorry, but the fault was all mine, the real code looked something like

  file: func.R
  make_plot <- function(data){
    p <- ggplot(...)
    p + geom_vline ...
    print(p)
    return(p)
  }

  source('func.R')
  p <- make_plot(data)
  ggsave('somewhere.png', plot=p)

So the retuned graphic object really was just empty. It should obviously have been

 p <- ggplot(...)
 p <- p + geom_vline ...

thank you very much!

Manuel Pasieka
Manuel Pasieka
December 29, 2017 15:24 PM

Related Questions


R - How to find points within specific Contour

Updated May 28, 2015 23:11 PM

How to see the code of a stored plot (ggplot)

Updated May 29, 2015 01:11 AM

R ggplot remove certain items from legend

Updated April 03, 2015 23:11 PM

add second axis label

Updated April 10, 2015 23:11 PM

Error in facet_grid in ggplot2

Updated October 09, 2016 09:11 AM