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]])
})