I'm developing a Shiny app that uses highcharter
pkg for data vis. I want to synchronise 2 highchart
plots so that when I change a date range in one plot (using range selector at the bottom of the plot, not range selector buttons), the second plot applies them, too. I read about afterSetExtremes()
JS function that captures min and max dates (example here ) that was suggested in this SO answer, but I'm not sure how I can apply this JS code to my R/Shiny code.
Below is a simple example of two highchart
plots that should be in sync
library(shiny)
library(highcharter)
data(fdeaths)
data(mdeaths)
ui <- fluidPage(
highchartOutput('f_plot'),
highchartOutput('m_plot')
)
server <- function(input, output, session) {
output$f_plot <- renderHighchart(
highchart(type = 'stock') %>%
hc_add_series(fdeaths)
)
output$m_plot <- renderHighchart(
highchart(type = 'stock') %>%
hc_add_series(mdeaths)
)
}
shinyApp(ui, server)
Thanks for any pointers.
You can use xAxis.events.afterSetExtremes event to fire the function that will update extremes of the second chart every time we change extremes of the first one. Of course, you can adapt this logic to change the extremes of the first chart when dragging the second one or do the same with a bigger amount of charts.
This is an example of how to do this in pure JavaScript: https://jsfiddle.net/BlackLabel/yg50ue1c/
And here you have an R implementation:
library(shiny)
library(highcharter)
data(fdeaths)
data(mdeaths)
ui <- fluidPage(
highchartOutput('f_plot'),
highchartOutput('m_plot')
)
server <- function(input, output, session) {
output$f_plot <- renderHighchart(
highchart(type = 'stock') %>%
hc_add_series(fdeaths) %>%
hc_xAxis(
events = list(
afterSetExtremes = JS("function(e) {
Highcharts.charts[0].xAxis[0].setExtremes(e.min, e.max);
}")
)
)
)
output$m_plot <- renderHighchart(
highchart(type = 'stock') %>%
hc_add_series(mdeaths) %>%
hc_xAxis(
events = list(
afterSetExtremes = JS("function(e) {
Highcharts.charts[1].xAxis[0].setExtremes(e.min, e.max);
}")
)
)
)
}
shinyApp(ui, server)
Note that Shiny differs a little and changes the order of charts so the second chart instance can be found here: Highcharts.charts[0] but the first here: Highcharts.charts[1] I wonder what the order would be if we had more charts...
API Reference: https://api.highcharts.com/highcharts/xAxis.events.afterSetExtremes https://api.highcharts.com/class-reference/Highcharts.Axis#setExtremes