for循环以在R中绘制图形

时间:2020-03-30 20:26:07

标签: r ggplot2

我有一个看起来像这样的数据集

a    b    c    d
x    1.1  lol  xyz
x    1.4  lal  xyw
y    1.2  lel  xyz
x    1.4  lol  xyw
y    1.8  lel  xyz

我得到ggplot(filter(df, c=="lol"), aes(x=b)) + geom_bar() + facet_wrap( ~ d) + xlab("xlab") + ylab ("ylab")的情节。 我正在尝试使用for循环针对每个c因子绘制此图,但是我不确定如何执行此操作。

1 个答案:

答案 0 :(得分:1)

plot_list = list()
for(uniq_c in unique(df$c)) {
  plot_list[[uniq_c]] = ggplot(filter(df, c == uniq_c), aes(x = b)) +
    geom_bar() +
    facet_wrap( ~ d) +
    xlab("xlab") + ylab ("ylab")
}

print(plot_list[["lal"]]) # print a single plot
lapply(plot_list, print)  # print all plots