Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Created January 15, 2017 14:02
Show Gist options
  • Save matt-dray/bdecd24d239c72154920f164ecc285b2 to your computer and use it in GitHub Desktop.
Save matt-dray/bdecd24d239c72154920f164ecc285b2 to your computer and use it in GitHub Desktop.
Plot each y column against x and arrange in grids over multiple pages
library(ggplot2) # for plotting
library(gridExtra) # for arranging plots
# Create example dataframe
df <- data.frame(x = letters[1:10]
, y1 = sample(1:100, 10)
, y2 = sample(1:100, 10)
, y3 = sample(1:100, 10)
, y4 = sample(1:100, 10)
, y5 = sample(1:100, 10)
)
# Loop through plots of each y col against x
ycols <- select(df, num_range("y", 1:5)) # columns to loop through
plot_list <- list() # create empty list, which is filled by the loop
for (i in seq_along(1:length(y_cols))) {
g <- ggplot(df, aes(x, y_cols[i])) +
geom_bar(stat = "identity") +
labs(y = paste0("axis_", names(y_cols[i]))) # plot with custom y label
name <- paste0("plot_", names(y_cols[i])) # create name for the plot
assign(name, g) # give the name to the plot
plot_list[[name]] <- g # fill list with each ggplot object
}
# Create 2x2 grid of the plots in plot_list
# New pages are created if there are more plots than nrow*ncol
gridExtra::marrangeGrob(plot_list, nrow = 2, ncol = 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment