diff --git a/R/proxy.R b/R/proxy.R index fe15018..bcd7425 100644 --- a/R/proxy.R +++ b/R/proxy.R @@ -217,3 +217,27 @@ ax_proxy_options <- function(proxy, options) { + + +#' @title Toggle series with proxy +#' +#' @description This method allows you to toggle the visibility of series programmatically. +#' Useful when you have a custom legend. +#' +#' @param proxy A \code{apexchartProxy} \code{htmlwidget} object. +#' @param series_name The series name which you want to toggle visibility for. +#' +#' @noRd +#' +#' @example examples/proxy-toggle.R +ax_proxy_toggle_series <- function(proxy, series_name) { + .ax_proxy2( + proxy = proxy, + name = "toggle-series", + l = list(seriesName = list1(series_name)) + ) +} + + + + diff --git a/examples/proxy-toggle.R b/examples/proxy-toggle.R new file mode 100644 index 0000000..8e06769 --- /dev/null +++ b/examples/proxy-toggle.R @@ -0,0 +1,43 @@ + +library(shiny) +library(apexcharter) + + +# data +data("economics_long", package = "ggplot2") + + +ui <- fluidPage( + tags$h2("Toggle series"), + fluidRow( + column( + width = 3, + actionButton("toggle", "Show/hide pop serie") + ), + column( + width = 9, + apexchartOutput(outputId = "chart") + ) + ) +) + +server <- function(input, output, session) { + + output$chart <- renderApexchart({ + apex( + data = economics_long, + type = "line", + mapping = aes(x = date, y = value01, group = variable), + auto_update = FALSE + ) %>% + ax_yaxis(decimalsInFloat = 2) + }) + + observeEvent(input$toggle, { + apexchartProxy("chart") %>% + ax_proxy_toggle_series(series_name = "pop") + }) + +} + +shinyApp(ui, server) \ No newline at end of file diff --git a/inst/htmlwidgets/apexcharter.js b/inst/htmlwidgets/apexcharter.js index 32ed06d..aa723aa 100644 --- a/inst/htmlwidgets/apexcharter.js +++ b/inst/htmlwidgets/apexcharter.js @@ -4,6 +4,8 @@ * https://github.com/dreamRs/apexcharter * */ + +/*global HTMLWidgets, ApexCharts, Shiny */ /// Functions @@ -280,7 +282,7 @@ HTMLWidgets.widget({ x.auto_update.options_animate, x.auto_update.update_synced_charts ) - .then(function(a, b) { + .then(function(chart) { exportChart(x, chart); }); } @@ -333,5 +335,16 @@ if (HTMLWidgets.shinyMode) { chart.updateOptions(obj.data.options); } }); + + // toggle series + Shiny.addCustomMessageHandler("update-apexchart-toggle-series", function(obj) { + var chart = get_widget(obj.id); + if (typeof chart != "undefined") { + var seriesName = obj.data.seriesName; + for(var i = 0; i < seriesName.length; i++) { + chart.toggleSeries(seriesName[i]); + } + } + }); }