I have a question about creating ggplot2 graphs in a for loop, renaming them based on the iteration and then arranging the graphs in a grid.
I want to do something like this dummy example
library(ggplot2)
a = c(1, 2, 3)
开发者_C百科
b = c(4, 5, 6)
for ( i in c(1:5)){
x = i*a
y = i*b
p = qplot(x, y)
... do something to rename p as plot_i...
}
... do something to arranage plots plot_1
... plot_6
into a 2 x 3 grid
Any suggestions?
You could save the plots into a list:
library(ggplot2)
library(gridExtra)
a <- c(1, 2, 3)
b <- c(4, 5, 6)
out <- NULL
for (i in 1:10){
take <- data.frame(a = a * i, b = b * i)
out[[i]] <- ggplot(take, aes(x = a, y = b)) + geom_point()
}
grid.arrange(out[[1]], out[[10]], out[[2]], out[[5]], nrow = 2)
An alternative way of approaching this problem is to use use facets in your plot:
a <- 1:3
b <- 4:6
# Create an empty data.frame
pdata <- data.frame()
for( i in 1:6){
# Create a temporary data.frame to store data for single plot
tmp <- data.frame(
plot = i,
x = i*a,
y = i*b
)
# Use rbind to add this plot data
pdata <- rbind(pdata, tmp)
}
# Plot results using ggplot with facets
ggplot(pdata, aes(x=x, y=y)) + geom_point() + facet_wrap(~plot)
The cowplot library has the plot_grid
function that will do this nicely:
library(ggplot2)
library(cowplot)
makeplot <- function(i, a=c(1,2,3), b=c(4,5,6)) {
take <- data.frame(a=a*i, b=b*i)
ggplot(take, aes(x=a, y=b)) + geom_point()
}
nums = 1:10
plots <- lapply(nums, makeplot)
plot_grid(plotlist = plots)
精彩评论