Несколько линий / трасс для каждой кнопки в выпадающем меню Plotly в R - PullRequest
0 голосов
/ 25 февраля 2019

Я пытаюсь создать несколько графиков в Plotly для 30 различных офисов продаж.Каждый график будет иметь 3 строки: продажи, COGS и инвентарь.Я хотел бы сохранить это на одном графике с 30 кнопками для разных офисов.Это самое близкое решение, которое я мог найти на SO:

 ## Create random data. cols holds the parameter that should be switched
l <- lapply(1:100, function(i) rnorm(100))
df <- as.data.frame(l)
cols <- paste0(letters, 1:100)
colnames(df) <- cols
df[["c"]] <- 1:100

## Add trace directly here, since plotly adds a blank trace otherwise
p <- plot_ly(df,
      type = "scatter",
      mode = "lines",
      x = ~c, 
      y= ~df[[cols[[1]]]], 
      name = cols[[1]])
## Add arbitrary number of traces
## Ignore first col as it has already been added
for (col in cols[-1]) {
  p <- p %>% add_lines(x = ~c, y = df[[col]], name = col, visible = FALSE)
}

p <- p %>%
    layout(
      title = "Dropdown line plot",
      xaxis = list(title = "x"),
      yaxis = list(title = "y"),
      updatemenus = list(
        list(
            y = 0.7,
            ## Add all buttons at once
            buttons = lapply(cols, function(col) {
              list(method="restyle", 
                args = list("visible", cols == col),
                label = col)
            })
        )
      )
    )

print(p)

. Это работает, но только на графиках с одиночными линиями / трассами.Как я могу изменить этот код, чтобы сделать то же самое, но с графиками с 2 или более трасс?или есть лучшее решение?Любая помощь будет оценена!

### EXAMPLE 2

#create fake time series data
library(plotly)
set.seed(1)
df <- data.frame(replicate(31,sample(200:500,24,rep=TRUE)))
cols <- paste0(letters, 1:31)
colnames(df) <- cols


#create time series

timeseries <- ts(df[[1]], start = c(2018,1), end = c(2019,12), frequency = 12)

fit <- auto.arima(timeseries, d=1, D=1, stepwise =FALSE, approximation = FALSE)
fore <- forecast(fit, h = 12, level = c(80, 95))


## Add trace directly here, since plotly adds a blank trace otherwise

p <- plot_ly() %>%
  add_lines(x = time(timeseries), y = timeseries,
            color = I("black"), name = "observed") %>%
  add_ribbons(x = time(fore$mean), ymin = fore$lower[, 2], ymax = fore$upper[, 2],
              color = I("gray95"), name = "95% confidence") %>%
  add_ribbons(x = time(fore$mean), ymin = fore$lower[, 1], ymax = fore$upper[, 1],
              color = I("gray80"), name = "80% confidence") %>%
  add_lines(x = time(fore$mean), y = fore$mean, color = I("blue"), name = "prediction")


## Add arbitrary number of traces
## Ignore first col as it has already been added

for (col in cols[2:31]) {


  timeseries <- ts(df[[col]], start = c(2018,1), end = c(2019,12), frequency = 12)


  fit <- auto.arima(timeseries, d=1, D=1, stepwise =FALSE, approximation = FALSE)
  fore <- forecast(fit, h = 12, level = c(80, 95))

  p <- p %>%
    add_lines(x = time(timeseries), y = timeseries,
              color = I("black"), name = "observed", visible = FALSE) %>%
    add_ribbons(x = time(fore$mean), ymin = fore$lower[, 2], ymax = fore$upper[, 2],
                color = I("gray95"), name = "95% confidence", visible = FALSE) %>%
    add_ribbons(x = time(fore$mean), ymin = fore$lower[, 1], ymax = fore$upper[, 1],
                color = I("gray80"), name = "80% confidence", visible = FALSE) %>%
    add_lines(x = time(fore$mean), y = fore$mean, color = I("blue"), name = "prediction", visible = FALSE)

}

p <- p %>%
  layout(
    title = "Dropdown line plot",
    xaxis = list(title = "x"),
    yaxis = list(title = "y"),
    updatemenus = list(
      list(
        y = 0.7,
        ## Add all buttons at once
        buttons = lapply(cols, function(col) {
          list(method="restyle", 
               args = list("visible", cols == col),
               label = col)
        })
      )
    )
  )
p

1 Ответ

0 голосов
/ 25 февраля 2019

Вы были очень близки!Например, если вам нужны графики с 3 трассами, вам нужно настроить только две вещи:

  1. Установить видимыми три первые трассы,
  2. Изменить кнопки, чтобы отображать трассы в группах по три.

Мой код:

## Create random data. cols holds the parameter that should be switched
library(plotly)
l <- lapply(1:99, function(i) rnorm(100))
df <- as.data.frame(l)
cols <- paste0(letters, 1:99)
colnames(df) <- cols
df[["c"]] <- 1:100

## Add trace directly here, since plotly adds a blank trace otherwise
p <- plot_ly(df,
             type = "scatter",
             mode = "lines",
             x = ~c, 
             y= ~df[[cols[[1]]]], 
             name = cols[[1]])
p <- p %>% add_lines(x = ~c, y = df[[2]], name =  cols[[2]], visible = T)
p <- p %>% add_lines(x = ~c, y = df[[3]], name =  cols[[3]], visible = T)
## Add arbitrary number of traces
## Ignore first col as it has already been added
for (col in cols[4:99]) {
  print(col)
  p <- p %>% add_lines(x = ~c, y = df[[col]], name = col, visible = F)
}

p <- p %>%
  layout(
    title = "Dropdown line plot",
    xaxis = list(title = "x"),
    yaxis = list(title = "y"),
    updatemenus = list(
      list(
        y = 0.7,
        ## Add all buttons at once
        buttons = lapply(0:32, function(col) {
          list(method="restyle", 
               args = list("visible", cols == c(cols[col*3+1],cols[col*3+2],cols[col*3+3])),
               label = paste0(cols[col*3+1], " ",cols[col*3+2], " ",cols[col*3+3] ))
        })
      )
    )
  )

print(p)

PD: я использую только 99 столбцов, потому что хочу 33 группы по 3 графика

...