简体   繁体   English

如何使用 lapply 遍历 ggplot2 中的 2 个变量

[英]How to loop through 2 variables in ggplot2 using lapply

Hi I got two parameters in my ggplot2 and want to create a list object for all the plots.嗨,我的 ggplot2 中有两个参数,并想为所有地块创建一个列表 object。 Somehow it gives me an error不知何故,它给了我一个错误

data = data.frame(date = rep(seq(as.Date('2020-01-01'), 
                                 as.Date('2020-01-07'),length.out =7),2), 
                             METRIC_NAME = rep(c('a','b','c','d','e','f','g'),2), 
                             METRIC_VALUE = seq(1,14,1), DIMENSION = rep(c('A','B'),7))
                  all_dimensions = unique(data$DIMENSION)
                  all_metric = unique(data$METRIC_NAME)
                  
                  
                  
                  plot_function = function(x,y){
                    p = ggplot(subset(data, METRIC_NAME == x & DIMENSION == y),
                               aes(x = DATE, y = METRIC_VALUE,
                                   color = DIMENSION_VALUE))+ geom_line() + 
                      scale_x_date(breaks = date_breaks("week"),
                                   labels = date_format("%d-%b"),
                                   minor_breaks = date_breaks("1 day"))+
                      facet_wrap(dim~., scales = 'free')
                    return (p)}
                  
                  
                  lapply(all_metric, function(x){lapply(all_dimensions, 
                                                        function(y)plot(x,y))} )

The error is错误是

Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:

You can split the dataset for each combination of group and use map to apply the plot function to each group.您可以为每个组组合拆分数据集,并使用map将 plot function 应用于每个组。

library(tidyverse)

data %>%
  group_split(DIMENSION, METRIC_NAME) %>%
  map(function(x){
      ggplot(x,aes(x = date, y = METRIC_VALUE, 
                   color = DIMENSION_VALUE))+ geom_line() + 
        scale_x_date(breaks = date_breaks("week"),
                     labels = date_format("%d-%b"),
                     minor_breaks = date_breaks("1 day"))+
        facet_wrap(DIMENSION~., scales = 'free')
}) -> list_plots

list_plots

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM