2011-05-28 41 views
2

我有一個關於在for循環中創建ggplot2圖形的問題,根據迭代重命名它們,然後將這些圖形排列在網格中。在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... 

} 

...做一些事情來arranage地塊plot_1 ... plot_6成2×3格

有什麼建議?

回答

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) 
2

處理這個問題的另一種方法是在你的陰謀使用用途方面:

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) 

enter image description here

+0

感謝這兩個回覆 - 他們正是我要找的 – Ross 2011-05-29 03:42:12

1

cowplot庫有plot_grid函數,這將很好地做到這一點:

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) 

enter image description here