Reputation: 15
How can I add a new series in a plot made by Highcharts? I want to do it by clicking on the button named "shux", created in Shiny.
Example data DF1
:
DF1 <- data.frame(
Date = c(as.Date("2017-12-01"), as.Date("2017-12-06"), as.Date("2017-12-11")),
Value = c(95,97,96)
)
Structure:
Date Value
1 2017-12-01 95
2 2017-12-06 97
3 2017-12-11 96
I want to add similar data DF2
(dataframe with 2 columns) to the plot.
My code:
library(shiny)
library(highcharter)
ui <- fluidPage(
titlePanel("Example"),
sidebarLayout(
sidebarPanel(
actionButton("shux", label = "Add")
),
mainPanel(
highchartOutput("hcontainer1", height = "800px")
)
)
)
server = function(input, output, session) {
output$hcontainer1 <- renderHighchart({
hc <- highchart() %>%
hc_add_series(
name = 'first',
data = DF1,
hcaes(x= Date, y = Value),
type = 'line'
)
})
}
shinyApp(ui = ui, server = server)
I tried:
observe({
input$shux
hc_add_series(
name = 'second',
data = DF2,
hcaes(x= Date, y = Value),
type = 'line'
)
})
But it didn't work. What approach should I use?
Upvotes: 1
Views: 1209
Reputation: 29387
Something like this do, please note that when you use renderHighchart
the chart will be redrawn.
library(shiny)
library(highcharter)
DF1 <- data.frame(
Date = c(as.Date("2017-12-01"), as.Date("2017-12-06"), as.Date("2017-12-11")),
Value = c(95,97,96)
)
DF2 <- data.frame(
Date = c(as.Date("2017-12-01"), as.Date("2017-12-06"), as.Date("2017-12-11")),
Value = c(75,77,76)
)
ui <- fluidPage(
titlePanel("Example"),
sidebarLayout(
sidebarPanel(
actionButton("shux",label = "Add")
),
mainPanel(
highchartOutput("hcontainer1", height = "800px")
)
)
)
server = function(input, output, session) {
hc <- reactive({
highchart() %>% hc_add_series(name = 'first',id = "1",data = DF1,hcaes(x= Date, y = Value),type = 'line')
})
hcadd <- eventReactive(input$shux,{
hc() %>% hc_add_series(name = 'second',id = "2",data = DF2,hcaes(x= Date, y = Value),type = 'line')
})
output$hcontainer1 <- renderHighchart({
if(input$shux == 0){
return(hc())
}
hcadd()
})
}
shinyApp(ui = ui, server = server)
Upvotes: 1