[英]How to loop through 2 variables in ggplot2 using lapply
嗨,我的 ggplot2 中有兩個參數,並想為所有地塊創建一個列表 object。 不知何故,它給了我一個錯誤
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))} )
錯誤是
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
您可以為每個組組合拆分數據集,並使用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.