如何在循环中绘制一系列ggplots

时间:2015-05-26 02:45:03

标签: r loops ggplot2

我有一个包含以下列的数据集:“站点”(15个位置),“Real_date”(采样日期)和“SL_mm”(对象大小) 我想为每个网站制作一个geom_boxplot的图表。每个站点的每个日期都有一个箱线图(每个站点的日期不同)

num = unique(sub2008$Site)
library(ggplot2)
ls=list()
for (i in 1:length(num)){
  df = subset(sub2008, sub2008$Site == num[i])
  ggplot(df) + geom_boxplot(aes(factor(real_date), SL_mm)) + 
    theme_classic() + 
    labs(title = paste0(num[i], ' 2008'))
}

但没有绘制图表。我可能错过了什么。当我使用plot()但不确定如何处理par()时,它适用于ggplot函数(我知道multiplot函数,但不知道如何将其合并到循环中)

1 个答案:

答案 0 :(得分:2)

sub2008 <- data.frame(
  Site = c("a","a","a","b","b","c","c","c","c"),
  real_date = c(1,2,3,4,5,6,7,8,9),
  SL_sm = c(4,2,4,1,2,4,7,4,10)
)

num = unique(sub2008$Site)
ls=list()
for (i in 1:length(num)){
  df = subset(sub2008, sub2008$Site == num[i])
  plot <- ggplot(df) + geom_boxplot(aes(factor(real_date), SL_sm)) +
    theme_classic() + 
    labs(title = paste0(num[i], ' 2008'))
  print(plot)
}

在循环内,图表不会自动打印。您必须明确使用print方法。

此外,您的代码中的变量是“SL_sm”,但在您的问题中,您将其称为“SL_mm”,因此请仔细检查您是否一致地引用它。

根据评论者的建议,这是一个很好的分面用例:

sub2008 <- data.frame(
  Site = c("a","a","a","b","b","c","c","c","c"),
  real_date = c(1,2,3,4,5,6,7,8,9),
  SL_sm = c(4,2,4,1,2,4,7,4,10)
)
plot1 <- ggplot(sub2008) + geom_boxplot(aes(factor(real_date), SL_sm)) +
  theme_classic() +
  labs(title = paste0(num[i], ' 2008')) +
  facet_grid(Site~.)
print(plot1)
plot2 <- ggplot(sub2008) + geom_boxplot(aes(factor(real_date), SL_sm)) +
  theme_classic() +
  labs(title = paste0(num[i], ' 2008')) +
  facet_grid(.~Site)
print(plot2)