0

I have a code which produces several bar plots with lapply. In this code I want to automatically specify units, width, height and resolution for my pngs with ggsave (I need to adjust the proportions of the pictures I produce, because some weeks ago I already produced hundreds of emf-pictures and came to the conclusion that png is the better format).

My question is related to a former post of mine (R: Producing several barcharts with ggplot2 and lapply: how to insert the subtitles according to a list?), but this post here is more about pngs.

If I don't use lapply and make my bar plot by bar plot, this works perfectly fine: First I set my working Directory, then I specify my png, and I close the device again:

png(filename="190709_bp_DA_MQ.png",units = "in",width=10, height=7,res = 120)

But with lapply and ggplot (ggsave and paste) it does not work anymore. I get the following Error

Error in grDevices::png(..., res = dpi, units = "in") : formal argument "res" matched by multiple actual arguments

###producing some random data
df <- data.frame(
  value = floor(runif(20,min=0,max=30)),
  Intervall = paste("Intervall",rep(1:10,2)), 
  type = rep(c("a", "b"))
)

list1 <- split(df, df$type)

###producing plots with lapply and ggplot
path <- ("S:/")
plots <- lapply(names(list1), function(nm) {
  ggplot(list1[[nm]], aes(Intervall, value)) + 
    geom_bar(stat = "identity") + 
    labs(title = "Intervalle", subtitle = nm)
})
names(plots) <- names(list1)

plots

#saving as pngs
lapply(names(plots), function(nm) { 
  ggsave(filename = paste(path, nm, ".png", sep = ""), 
         width = 10, height = 7, plot = plots[[nm]])
})


#If I only specify width and height, the code works. 

#But: I want to have the units in Inches and also add the resolution. if I add #units and resolution, the code doesnt work anymore. 

lapply(names(plots), function(nm) {
  ggsave(filename = paste(path,nm, ".png", sep = ""), 
         units = "in", width = 10, height = 7, res = 120, plot = plots[[nm]])
})
Leonardo
  • 2,439
  • 33
  • 17
  • 31
C Ec
  • 23
  • 3
  • 3
    The resolution parameter of `ggsave` is `dpi` not `res`. Also, what exactly does "the code doesnt work" mean? – Roland Jul 22 '19 at 11:13
  • the code not working means, I guess, that the error mentioned in the question is returned ;-) But this should disappear with using `dpi` – TobiO Jul 22 '19 at 13:33
  • the error itself means, that there are several arguments specified in the function that can be matched by `res`. See 4th slide in here https://www.stat.berkeley.edu/~statcur/Workshop2/Presentations/functions.pdf – TobiO Jul 22 '19 at 13:37
  • Oh ok, easy solution! many thanks to both of you, now it worked:)! – C Ec Jul 23 '19 at 08:17

0 Answers0