【问题标题】:How to map tibble elements to ggplot2 aesthetics?如何将 tibble 元素映射到 ggplot2 美学?
【发布时间】:2017-08-22 21:24:10
【问题描述】:

我有以下数据集

map(.x = list(small = 3, medium = 10, large  = 100) , 
      .f = ~ sample(rnorm(1000), .x, replace = T)) %>% 
      tibble(sample = ., mean = map_dbl(., mean)) 

# A tibble: 3 x 2
       sample       mean
       <list>      <dbl>
1   <dbl [3]> 0.61473548
2  <dbl [10]> 0.17278357
3 <dbl [100]> 0.04156308

我正在尝试在 ggplot2 中为 sample 列中的每条记录在功能上创建 1 个直方图。我想在同一个网格中显示图,因此我想我可以以某种方式使用facet_wrap(),但我不确定如何将美学映射到列表。

这是我迄今为止尝试过的:

map(.x = list(small = 3, medium = 10, large  = 100) , 
          .f = ~ sample(rnorm(1000), .x, replace = T)) %>% 
          tibble(sample = ., mean = map_dbl(., mean)) %>% 
   ggplot2::ggplot(data = .) + geom_histogram(mapping = aes(sample)) + facet_wrap(~ sample)

我期望的输出是 3 个直方图,分别有 3、10 和 100 个观察值。

我想知道是否可能的解决方案是将sample 分成两列:一列包含所有值,另一列指示每个值所属的分布大小。这可能更符合 ggplot2 逻辑,但我不确定如何相应地扩展 tibble。

ps:我不知道如何表达这个问题欢迎任何建议

【问题讨论】:

    标签: r ggplot2 purrr


    【解决方案1】:

    我觉得你需要tidyr::unnest:

    library(dplyr)
    library(tidyr)
    library(ggplot2)
    
    ## generate data
    set.seed(123)
    dtf <- map(.x = list(small = 3, medium = 10, large  = 100),
               .f = ~ sample(rnorm(1000), .x, replace = T)) %>%
        tibble(sample = ., mean = map_dbl(., mean))
    
    ## plot
    dtf %>%
        mutate(group = names(sample)) %>%  # or: group = lengths(sample)
        unnest(sample) %>%
        ggplot(data = .) +
        geom_histogram(mapping = aes(sample)) +
        facet_wrap(~ group)
    

    【讨论】:

      【解决方案2】:

      列表结构给你带来了问题。试试这个:

          tibble(id = rep(c("small", "medium", "large"), c(3,10,100)),
             samples = sample(rnorm(1000), 113, replace = T)) %>%
      ggplot2::ggplot(data = .) + 
          geom_histogram(mapping = aes(samples)) + facet_wrap(~ id)
      

      【讨论】:

      • +1 因为这实际上非常接近我正在做的事情,但它不是很普遍。例如,对于replace = F,相同的值不可能出现在两个不同的图中。相反,我可能希望replace=F 在同一个地块内,而不是在地块之间。
      • 嗯,我明白了。您可以多次调用 sample 并连接结果。 dist &lt;- rnorm(1000); samples &lt;- c(sample(dist,3), sample(dist,10), sample(dist,100));
      猜你喜欢
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 2019-03-21
      • 2023-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多