简体   繁体   English

如何在 R 中使用 autoplot + facet_wrap 绘制选定的图?

[英]How can I plot selected plot using autoplot + facet_wrap in R?

all.全部。

I need to plot selected one.我需要绘制选定的一个。 I can plot all, but I can not fine how to plot what I select.我可以绘制所有内容,但我不知道如何绘制我选择的内容。

for example...例如...

date <- as.Date('2021-01-01') + 0:4
category <- c(rep("A",5), rep("B",5), rep("C",5), rep("D",5), rep("E",5))
product <- c("A1","A2","A3","A4","A5",
             "B1","B2","B3","B4","B5",
             "C1","C2","C3","C4","C5",
             "D1","D2","D3","D4","D5",
             "E1","E2","E3","E4","E5")
value <- rnorm(25,10,1)
df <- data.frame(date, category, product, value)

first of all, I made simple tiny dataset.首先,我制作了简单的微型数据集。 and convert tsibble object.并转换 tsibble 对象。 (my data is times series.) (我的数据是时间序列。)

df <- tsibble(df, key = c(category, product), index = date)
df_h <- df %>% aggregate_key(category / product, value = sum(value))

and I use aggregate_key() function to make hierarchical time-series.我使用aggregate_key()函数来制作分层时间序列。

df_h %>% autoplot(value) + facet_wrap(~ category, scales = "free_y")

then.. plot it using autoplot() function plus facet_wrap()然后.. 使用autoplot()函数加上facet_wrap()绘制它

the results shows 6 plots (aggregated + 5 categories), I need to plot selected category (among A to E) only.结果显示 6 个图(聚合 + 5 个类别),我只需要绘制选定的类别(A 到 E)。

thanks, all.谢谢大家

..updated ..更新

date <- as.Date('2021-01-01') + 0:4
category <- c(rep("A",5), rep("B",5), rep("C",5), rep("D",5), rep("E",5))
product <- c("A1","A2","A3","A4","A5",
             "B1","B2","B3","B4","B5",
             "C1","C2","C3","C4","C5",
             "D1","D2","D3","D4","D5",
             "E1","E2","E3","E4","E5")
value <- rnorm(25,10,1)


df <- data.frame(date, category, product, value)


df <- tsibble(df, key = c(category, product), index = date)


df_h <- df %>% aggregate_key(category / product, value = sum(value))


df_h %>% 
    filter(category == "A" | category == "C" | category == "E") %>% 
    autoplot(value) + facet_wrap(~ category, scales = "free_y" , ncol = 2)

just temporary.. using filter() function, I can plot what I selected.只是暂时的.. 使用filter()函数,我可以绘制我选择的内容。 but it looks not good.但它看起来不太好。 I think there is more elegant way to handle it.我认为有更优雅的方式来处理它。

date <- rep(as.Date('2021-01-01') + 0:4, 5)
category <- c(rep("A",5), rep("B",5), rep("C",5), rep("D",5), rep("E",5))
product <- c("A1","A2","A3","A4","A5",
             "B1","B2","B3","B4","B5",
             "C1","C2","C3","C4","C5",
             "D1","D2","D3","D4","D5",
             "E1","E2","E3","E4","E5")
value <- rnorm(25,10,1)

tibble(date, category, product, value)|>
  tsibble(key = category, index = date)|>
  filter(category == "A" | category == "C" | category == "E") |> 
  autoplot(value) + facet_wrap(~ category, scales = "free_y" , ncol = 2)

Like this?像这样? :-) :-)

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

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