【问题标题】:How can I loop over values/factors in a variable in ggplot2?如何遍历 ggplot2 中变量中的值/因子?
【发布时间】:2018-10-16 10:13:53
【问题描述】:

使用iris 数据集..

示例代码和函数:

plotfunction <- function(whatspecies){

baz <- iris %>% filter(Species == whatspecies) %>% 
  ggplot(aes(Petal.Width, Petal.Length)) +
  geom_point() +
  labs(title = whatspecies)

ggsave(filename = paste0(whatspecies,".png"), 
       path = getwd())

return(baz)

}

我想做的是循环Species 变量以在我的工作目录中创建 3 个图。在我的真实数据框中,我有更多的因素,所以我想知道是否有更好的方法来做到这一点,而不是运行函数 n 次 - 因为在这种情况下,我只关心修改/循环每个图中的一个变量.

编辑:在我的情况下,我需要独立的情节,所以我不能使用方面或不同的美学。

【问题讨论】:

  • 您可以用多种颜色aes(color = Species) 或构面facet_wrap(~ Species) 绘制一次
  • @PoGibas 在我的情况下,我需要独立的情节,所以我不能使用方面或不同的美学。
  • @PoGibas 他可以,但这不是被问到的。
  • @snoram 我明白,只是想确保这不是最简单的解决方案。

标签: r for-loop ggplot2


【解决方案1】:

这是你要找的吗?

library(dplyr)
library(ggplot2)

for (sp in levels(iris[["Species"]])) {
  plotfunction(sp)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    相关资源
    最近更新 更多