【问题标题】:Repeat a ggplot for each value of a variable in the dataframe为数据框中变量的每个值重复一个 ggplot
【发布时间】:2021-05-16 09:59:08
【问题描述】:

我想为我的数据框中的每个变量值制作一个图表,然后将该值作为标题传递给图表。我认为最好的方法是使用apply() 系列函数,但我有点新手,不知道该怎么做。

例如,假设我有这个数据框:

df <- data.frame(month=c("Chair", "Table", "Rug", "Wardrobe", "Chair", "Desk", "Lamp", "Shelves", "Curtains", "Bed"),
                 cutlery=c("Fork", "Knife", "Spatula", "Spoon", "Corkscrew", "Fork", "Tongs", "Chopsticks", "Spoon", "Knife"),
                 type=c("bbb", "ccc", "aaa", "bbb", "ccc", "aaa", "bbb", "ccc", "aaa", "bbb"),
                 count=c(341, 527, 2674, 811, 1045, 4417, 1178, 1192, 4793, 916))

我可以手动检查并选择type 的值:

df %>% 
  filter(type=='aaa') %>% 
  ggplot() +
  geom_col(aes(month, count)) +
  labs(title = 'value of {{type}} being plotted')

df %>% 
  filter(type=='bbb') %>% 
  ggplot() +
  geom_col(aes(month, count)) +
  labs(title = 'value of {{type}} being plotted')

df %>% 
  filter(type=='ccc') %>% 
  ggplot() +
  geom_col(aes(month, count)) +
  labs(title = 'value of {{type}} being plotted')

但这很快就会变成大量代码,type 的级别足够高,并且假设每个情节都有相当数量的附加代码。我们还假设我不想使用facet_wrap(~type)。如您所见,x 变量的值在不同类型的值之间变化很大,因此facet_wrap() 导致沿 x 轴有很多缺失的空格。理想情况下,我只需要创建一个函数,将 x 和 y 变量和 type 作为输入,然后对 type 进行过滤,制作绘图,并提取 type 的值以在标题中使用。

谁能帮我解决这个问题?

【问题讨论】:

    标签: r ggplot2 dplyr apply


    【解决方案1】:

    或者您可以创建自定义函数,然后在type 的级别上创建lapply

    myplot <- function(var){
      df %>% 
        filter(type==var) %>% 
        ggplot() +
        geom_col(aes(month, count)) +
        labs(title = paste0("value of ",var))
    }
    plot.list <- lapply(unique(df$type), myplot)
    plot.list[[1]]
    plot.list[[2]]
    plot.list[[3]]
    

    编辑

    包含 x 变量作为参数::

    myplot <-
      function(var, xvar) {
        df %>%   
          filter(type == var) %>%   
          ggplot() + 
          geom_col(aes(x={{xvar}}, count)) +   
          labs(title = paste0("value of ", var))
      }
    
    plot.list <- lapply(unique(df$type), myplot,xvar=cutlery)
    

    你错过了{{}}(又名'curly curly')运算符,它取代了用enquo 引用和用!!(又名'bang-bang')取消引用的方法,并且参数xvar 必须作为lapply 的额外参数传递,而不是lapply 内部函数的额外参数

    【讨论】:

    • 所有答案都很棒。我热衷于使用 lapply()。我想知道是否有办法将 x 和 y 传递给 myplot 函数?说,像这样的事情(我试过运行它并返回一个错误,但希望很清楚我的意图是什么):myplot &lt;- function(var, x){ df %&gt;% filter(type==var) %&gt;% ggplot() + geom_col(aes(x, count)) + labs(title = paste0("value of ",var)) } plot.list &lt;- lapply(unique(df$type), myplot(x=cutlery))。我在上面的 df 中添加了一个额外的列,名为 cutlery
    【解决方案2】:

    您可以为type 的每个值拆分数据并生成图表列表。

    library(tidyverse)
    
    df %>%
      group_split(type) %>%
      map(~ggplot(.x) +
            geom_col(aes(month, count)) +
            labs(title = sprintf('value of %s being plotted', 
                                  first(.x$type)))) -> plot_list
    

    plot_list[[1]] 返回:

    plot_list[[2]] 返回 -

    【讨论】:

      【解决方案3】:

      根据您的声明“理想情况下,我只需要创建一个函数,将 x 和 y 变量作为输入,然后键入 ...”作为不同的变量(例如向量)作为输入,而不是将整个 dataframe 作为输入。在这种情况下,此功能可能适合您的需求:

      library(ggplot2)
      library(dplyr)
      
      myPlot_function = function(x, y, type) {
              
              gg_list = list() # empty list
              df = data.frame(x, y, type)
              type_n = length(unique(df$type)) # number of each type
              
              for (i in 1:type_n){ # loop over each type
                      
                      g = df %>%
                              filter(type == type[i]) %>%
                              ggplot() +
                              geom_col(aes(x, y)) +
                              labs(title = paste0("Value of ", type[i], " being plotted"))
                      gg_list[[paste0("plot_", i)]] = g
              }
              return(gg_list)
      }
      

      然后,您可以将 xytype 指定为向量。例如:

      some_plots = myPlot_function(x = df$month, y = df$count, type = df$type)
      

      函数myPlot_function 返回一个包含您的绘图的list。您现在可以使用some_plots$plot_1some_plots[[1]] 来查看您的情节。例如:

      some_plots$plot_1
      

      【讨论】:

        猜你喜欢
        • 2016-10-07
        • 2021-04-03
        • 2018-07-26
        • 1970-01-01
        • 1970-01-01
        • 2016-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多