【问题标题】:Pull title and subtitle from 2 different columns in a nested tibble从嵌套 tibble 的 2 个不同列中提取标题和副标题
【发布时间】:2019-09-09 20:07:27
【问题描述】:

我想使用两个常规字符列为嵌套 tibble 中的一系列图形创建标题和副标题。我可以使用 .x 和 .y 功能在标题中添加一列。例如:

    library(tidyverse)

    df <- mtcars %>%
      filter(carb %in% c(1, 2, 4)) %>%
      mutate(carb = as.character(carb), gear = as.character(gear))

    df_with_plots <- df %>% 
      group_by(carb, gear) %>% 
      nest() %>% 
      mutate(plot = map(data, function(.x) { 
        .x  %>%
          ggplot() +
          geom_histogram(aes(mpg))
      }))

df_with_plots
 carb  gear    data             plot  
  <chr> <chr> <list>           <list>
1 4     4     <tibble [4 × 9]> <gg>  
2 1     4     <tibble [4 × 9]> <gg>  
3 1     3     <tibble [3 × 9]> <gg>  
4 2     3     <tibble [4 × 9]> <gg>  
5 4     3     <tibble [5 × 9]> <gg>  
6 2     4     <tibble [4 × 9]> <gg>  
7 2     5     <tibble [2 × 9]> <gg>  
8 4     5     <tibble [1 × 9]> <gg>  

    figs <- map2(df_with_plots$plot, df_with_plots$gear, ~ .x + labs(title = paste("Number of gears", .y))) 

    figs[[1]] 

这将产生一系列数字,标题中带有“齿轮数”.y 的一系列数字。我怎样才能在标题中同时获得齿轮和碳水化合物(前两列)?

【问题讨论】:

  • 您需要在您的 mutate 中使用 map2。并且您的 .x 数据必须是 .x$col ,即在使用 map2 嵌套之后在 mutate 中使用 labs

标签: r ggplot2 tidyr


【解决方案1】:

这是我之前写过的东西,数据也是嵌套的数据框。我没有电脑,所以我无法创建您的示例。

plots_bar <- plots_bar_data %>% 
  mutate(plots = map2(data, Source, function(.x, .y){ .x %>% 
    ggplot(aes(x= .x$n, y=.x$nn)) +
  geom_bar(stat="identity", fill= farver[2]) + 
  geom_text(aes(label=.x$nn), vjust = -.5) +
  scale_y_continuous(breaks = seq(0, 45, 5)) +
  scale_x_continuous(breaks = seq(0, 24, 2)) +
  labs(y = "Antal dage", 
       x="Antal scanninger",
       title = paste0(.y, ": Antal dage med antal scanninger")) +
      my_theme
  }))


#   for(i in 1:4){
# print(plots_bar$plots[[i]])
# }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    相关资源
    最近更新 更多