1

I have a bunch of plots which I need to save in a given filename structure.

export_png <- function(p, fn, h, w){
  ggsave(filename = paste(fn, "-", date, ".png", sep = ""), plot = p,
         height = h,
         width = w
         )}

However, this requires that I define height and width for all plots at their call of this function. Since I am plotting time series with monthly incoming data, I would like to automatically set h & w.

For some with plots large legends, I stretch the plot via helper parameters dynamically...

export_png(p = large_plot, fn = "large",
  h = helper1,
  w = helper2)

...but some others don't really need them, because the legends are small and ggplot2's default dimension calculation is fine.

export_png(p = normal_plot, fn = "normal", h = N, w = M)

Is there some way to pass these plots' default dimensions into my function, so I don't have to determine N & M manually?

I've looked at two similar questions, but they utilise defined dimensions at some point.

Katrin Leinweber
  • 1,316
  • 13
  • 33
  • 1
    I think I need a concrete example to understand. Is there a characteristic of the plot object that you can look at to determine if it should be large or not? (Or is that what you are asking?) What do you mean by the "plots' default dimensions", where are these defined? – Gregor Thomas Sep 10 '15 at 17:11
  • 1
    See the din parameter for [par](http://www.inside-r.org/r-doc/graphics/par) to get what I think you mean by default dimensions. – blep Sep 10 '15 at 17:15
  • 1k thanks! `par` was what I needed :-) [Here's a (now) working example](https://github.com/KonScience/Summarize-Flattr-Reports/tree/develop). – Katrin Leinweber Sep 11 '15 at 08:26

1 Answers1

1

You can do this by using default arguments in your function:

export_png <- function(p, fn, h=par("din")[2], w=par("din")[1]){
    ggsave(filename = paste(fn, "-", date, ".png", sep = ""), plot = p,
           height = h,
           width = w
    )}

If you don't specify h and w when you call export_png, it will get the dimensions of the current plot.

blep
  • 726
  • 1
  • 11
  • 28
  • 1
    I should also mention that you haven't defined `date`, but I'm assuming it's a string. And if you're going to use sep="", you might look into `paste0` instead of `paste` - it's supposed to be more efficient. – blep Sep 10 '15 at 19:00