【问题标题】:Unable to loop through ggplot histogram无法循环通过ggplot直方图
【发布时间】:2019-03-19 12:35:02
【问题描述】:

我正在尝试遍历 iris 数据集的每一列并在 ggplot 中绘制直方图。所以我预计会出现 5 个不同的直方图。但是,我下面的 for 循环什么也不返回。我该如何解决这个问题?

library(ggplot2)

for (i in colnames(iris)){
  ggplot(iris, aes(x = i))+
    geom_histogram()
}

【问题讨论】:

  • 如果目标是仅使用ggplot(2),则无需加载整个tidyverse
  • 如果你真的想用 for 循环来做这件事,你可能不得不使用 aes_string 而不是 aes。但是为了获得理想的结果,我认为@Maurits Evers 的答案是更好的方法:)

标签: r for-loop ggplot2


【解决方案1】:

而不是使用for 循环,tidyverse/ggplot 的方式是将数据从宽调整为长,然后使用facet_wrap 进行绘图

library(tidyverse)
iris %>%
    gather(key, val, -Species) %>%
    ggplot(aes(val)) +
    geom_histogram(bins = 30) +
    facet_wrap(~key, scales = "free_x")

【讨论】:

    【解决方案2】:

    使用dplyrtidyrggplot

    library(ggplot2)
    library(dplyr)
    library(tidyr)
    
    iris %>% 
      gather(Mesure, Value, -Species) %>%
      ggplot(aes(x=Value)) + geom_histogram() + facet_grid(rows=vars(Species), cols=vars(Mesure))
    

    结果:

    【讨论】:

      猜你喜欢
      • 2013-04-08
      • 2017-07-02
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 2022-12-01
      • 2021-08-16
      • 1970-01-01
      • 2016-06-14
      相关资源
      最近更新 更多