I am trying to create a shiny app with a plotly output.
The plot should have multiple y axes, and update based on the variables selected.
The question is how to combine the shiny reactivity and plotly while using add_lines
, as at the moment if I select less variables than add_lines
the code does not function
Sample code:
library(shiny)
library(dplyr)
library(plotly)
library(tidyr)
data <- cbind(
seq(from = 1, to = 30, by = 1),
sample(seq(from = 100, to = 300, by = 10), size = 30, replace = TRUE),
sample(seq(from = 1, to = 100, by = 9), size = 30, replace = TRUE),
sample(seq(from = 50, to = 60, by = 2), size = 30, replace = TRUE),
sample(seq(from = 100, to = 130, by = 1), size = 30, replace = TRUE)
) %>%
as.data.frame()
names(data) <- c("date", "a", "b", "x", "y")
data <- data %>% gather("key", "value", 2:5)
ui <- fluidPage(
column(
width = 3,
selectInput("select", "Select var:", choices = c("a", "b", "x", "y"), selected = c("a", "b", "x"), multiple = TRUE)
),
column(
width = 9
),
column(
width = 12,
plotlyOutput("plot")
)
)
server <- function(input, output){
output$plot <- renderPlotly({
data <- data %>% filter(key %in% c("date", input$select)) %>% spread(key, value)
plot_ly(x = ~data$date) %>%
add_lines(y = ~data[, 2], name = input$select[1], line = list(color = "red")) %>%
add_lines(y = ~data[, 3], name = input$select[2], line = list(color = "blue"), yaxis = "y2") %>%
add_lines(y = ~data[, 4], name = input$select[3], line = list(color = "green"), yaxis = "y3") %>%
layout(
yaxis = list(
side = "left"
),
yaxis2 = list(
side = "left",
overlaying = "y",
anchor = "free",
position = 0.02
),
yaxis3 = list(
side = "left",
overlaying = "y",
anchor = "free",
position = 0.04
)
)
})
}
shinyApp(ui, server)