【问题标题】:How to plot hierarchical time series in Rmarkdown shinny如何在 Rmarkdown shinny 中绘制分层时间序列
【发布时间】:2021-01-06 23:06:33
【问题描述】:

我希望根据以下代码绘制包含在列表中的分层时间序列:
库和数据创建

title: "prueba shiny"
runtime: shiny
output: html_document
---
library(dplyr)
library(tidyr)
library(dygraphs)
library(tseries)

df <- data.frame(date = c(as.yearmon(2018,1),as.yearmon(2018,1),as.yearmon(2018,2),as.yearmon(2018,2),
                          as.yearmon(2018,1),as.yearmon(2018,1),as.yearmon(2018,2),as.yearmon(2018,2)),                sales = c(1,2,3,4),
                 cat_I = c("drink","drink","food","food","drink","drink","food","food"),
                 cat_II = c("cola","fanta","tomatoes","bananas","cola","fanta","tomatoes","bananas"))

cat <- data.frame(I = c("drink","drink","food","food"),
                  II = c("cola","fanta","tomatoes","bananas"))


为每个最终产品 (ts) 创建单独的时间序列:

ts <- list()
for(s in unique(cat$II)){
  aux <- df %>%  filter(cat_II==s) %>%  
    as.data.frame()
  ts[[s]] <- ts(aux$sales,start=c(2018,1),frequency = 12)
}

为端点产品 (ts_I_II) 创建分层列表并按类别分组

aux <- with(cat,split(II,I))
ts_I_II <-  lapply(aux, function(x) ts[x])

catI_sales <- list()
for (s in unique(cat$I)){
  catI_sales[[s]] <- do.call(cbind,ts_I_II[[s]])
}

想要的地块:
1 - 第一个图包含一个类别内的所有时间序列

aux <- do.call(cbind,ts_I_II$drink)
dygraph(aux, main = "sales by cat_II") %>% dyOptions(colors = RColorBrewer::brewer.pal(5, "Set2"))

2 - 秒图是最终产品时间序列

dygraph(ts_I_II$drink$cola, main = "sales by cat_II") %>% dyOptions(colors = RColorBrewer::brewer.pal(5, "Set2"))

我希望通过从 selectInput 中选择类别来创建这两个图。我尝试过这样的事情但没有成功:


selectInput("I", label = "category_I:",
           choices = unique(cat$I), selected = cat$I[1])
selectInput("II", label = "II", choices = unique(cat$II))

plotOutput(outputId = "dy")

data <- reactive({
  ts_I_II$input$II})

output$dy <- renderPlot({
   dygraph(data)

【问题讨论】:

    标签: plot shiny time-series r-markdown


    【解决方案1】:
    selectInput("II", label = "category_II:",
               choices = names(ts))
    
    
    dygraphs::renderDygraph({
      dygraph(ts[[input$II]])
    })
      
    selectInput("I", label = "category_I:",
               choices = names(catI_sales))
    
    
    dygraphs::renderDygraph({
      dygraph(catI_sales[[input$I]])
    })
      
    
    

    【讨论】:

      猜你喜欢
      • 2015-07-05
      • 2016-01-28
      • 2020-11-17
      • 2020-02-22
      • 1970-01-01
      • 2016-01-08
      • 2013-02-20
      • 2012-09-06
      • 2021-08-04
      相关资源
      最近更新 更多