我有一个关于在for循环中创建ggplot2图形的问题,根据迭代重命名它们,然后在网格中排列图形。
我想做类似虚拟示例的事情
library(ggplot2)
a = c(1, 2, 3)
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...
}
...做一些事情来将地块plot_1
...... plot_6
分成2 x 3网格
有什么建议吗?
答案 0 :(得分:4)
您可以将图表保存到列表中:
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)
答案 1 :(得分:2)
解决此问题的另一种方法是在图中使用facet:
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)