I produce nine ggplots
within a for loop and subsequently arrange those plots using grid.arrange
:
plot_list <- list()
for(i in c(3:ncol(bilanz.vol))) {
histogram <- ggplot(data = bilanz.vol, aes(x = bilanz.vol[,i])) +
geom_histogram() +
scale_x_log10() +
ggtitle(paste(varnames[i]))
# ggsave(filename = paste("Graphs/", vars[i], ".png", sep = ""), width = 16, height = 12, units = "cm")
plot_list <- c(plot_list, list(histogram))
}
library(gridExtra)
png(filename = "Graphs/non-mfi.png", width = 1280, height = 960, units = "px")
do.call(grid.arrange, c(plot_list, list(ncol = 3)))
dev.off()
The code itself works fine and there are no errors. But for some reason I do not understand, the grid shows the same (last) histogram nine times. Still, each plot shows the correct title.
Interestingly, when I uncomment the ggsave
line in the code above, each plot is saved correctly (separately) and shows the expected histogram.
Any ideas?
You can either print directly a ggplot into PNG/PDF files or use the convenient function ggsave() for saving a ggplot. The default of ggsave() is to export the last plot that you displayed, using the size of the current graphics device. It also guesses the type of graphics device from the extension.
Using the results from split() function, we can create a list of plots, ggplot objects, using map() function in purrr R package. In this example, map() makes a scatter plot for each species. Note that the first argument to ggplot() function is . x and it represents the smaller dataframe corresponding to each species.
For this function, we simply specify the different ggplot objects in order, followed by the number of columns (ncol) and numebr of rows (nrow). This function is awesome at aligning axes and resizing figures. From here, we can simply save the arranged plot using ggsave() .
To save multiple plots to the same page in the PDF file, we use the par() function to create a grid and then add plots to the grid. In this way, all the plots are saved on the same page of the pdf file. We use the mfrow argument to the par() function to create the desired grid.
The reason is that ggplot does not evaluate the expression in the aes
call before it is used (so I believe at least), it just sets up the plot and stores the data inside of it. In you case "the data" is the entire data frame bilanz.vol
and since i = ncol(bilanz.vol)
after the for
loop completes the expression bilanz.vol[,i]
will evaluate to the same thing for all plot objects.
To make it work you could do this, which makes sure all plot objects contains different data sets my.data
.
my.data <- data.frame(x = bilanz.vol[,i])
histogram <- ggplot(data = my.data, aes(x = x)) +
geom_histogram() +
scale_x_log10() +
ggtitle(paste(varnames[i]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With