简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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