Search code examples
rhighchartsshinyr-highcharter

Highcharter R custom button for log axis


I want user-selectable y-axis scale log/linear. I got the custom button code from the answer here and it's working for showing the custom buttons, but I can't the buttons to work (i.e. change the y-axis). I'm sure I saw them work once or twice, but not consistently and now they don't work at all, so I suspect there's an error in the syntax that I can't find. It works neither in the RStudio viewer or in a shiny app.

library(highcharter)
library(shiny)

ui <- fluidPage(
  mainPanel(
    highchartOutput("plot_hc")
  )
)

server <- function(input, output) {
  output$plot_hc <- renderHighchart({

  dl <- data.frame(x = 1:10, y = 2 ^ (10:1))

  highchart() %>%
    hc_add_series(dl, type = 'line', hcaes(x, y)) %>%
    hc_exporting(
       enabled = TRUE
      ,buttons = list(
         customButton = list(text = 'Linear'
                            ,onclick = JS("function() {this.yAxis[0].update({type: 'linear'});}")
                            )
        ,customButton = list(text = 'Log'
                            ,onclick = JS("function() {this.yAxis[0].update({type: 'logarithmic'});}")
                            )
        )
      )
  })
}

shinyApp(ui, server)

Solution

  • You can't have a duplicated key (customButton). Do:

    ,buttons = list(
      customButton = list(text = 'Linear'
                          ,onclick = JS("function() {this.yAxis[0].update({type: 'linear'});}")
      )
      ,customButton2 = list(text = 'Log'
                           ,onclick = JS("function() {this.yAxis[0].update({type: 'logarithmic'});}")
      )