Highcharter R bubbleLegend doesn't work when the x-axis is categorical

Viewed 111

I'm currently trying to create a Highcharts scatter plot that displays a bubble legend when the second variable is selected. When the second variable is selected, I add the size parameter to the hc_add_series(..., hcaes(size = var2)) function.

The issue is, when the first variable is a categorical/factor etc, then the plot renders incorrectly. The x-axis labels and points on the graph are all pushed to the left of the plot. It works as expected without the bubbleLegend enabled AND it works when the second variable isn't a categorial.

Since the app I'm actually working on is quite large, I've recreated the issue with some dummy code in a basic shiny app. This is my first question on SO, so please let me know if I need to provide more info. Thanks!

library(shiny)
library(highcharter)
library(data.table)

temp = as.data.table(iris)
choices = names(temp)[-1]

ui <- fluidPage(
  div(class="row",
      column(width = 3, fixedPanel(
          selectInput("in_var1","Select Grouping Variable 1:",
                      choices = choices,
                      selected = choices[4],
                      multiple = FALSE),
          selectInput("in_var2","Select Size Variable:",
                      choices =  c("\a", choices),
                      selected = NULL,
                      multiple = FALSE),
        width = "20%"
      )),
      column(width = 9,
             highchartOutput("scatter_plot",height = "500px"),
      ))
)
server <- function(input, output) {
  
  explore_scatterplot = function(data, var1, var2=NULL){
    in_data = copy(data)
    in_data[, var1 := get(var1)]
    if(var2 != "\a"){ in_data[, var2 := get(var2)]}
    
    # init hc object
    scp = highchart() %>%
      hc_yAxis(min = 0)
    
    if(var1 == "Species") {
      scp = scp %>% hc_xAxis(type = "category")
      in_data = in_data[order(var1)]
    }
    
    # build the plot based on which variables are selected
    if(var2 == "\a"){
      scp = scp %>%
        hc_add_series(data = in_data, hcaes(x = var1, y = Sepal.Length), type = "scatter", showInLegend = FALSE)
    } else {
      scp = scp %>%
        hc_add_series(data = in_data, hcaes(x = var1, y = Sepal.Length, size = var2), type = "scatter", 
                      maxSize = "10%", showInLegend = FALSE) %>%
        hc_legend(bubbleLegend = list(enabled = TRUE))
    }
    
    return(scp)
  }
  
  output$scatter_plot <- renderHighchart({
    validate(need(!is.null(input$in_var1) &
                  !is.null(input$in_var2), "Waiting on inputs..."))
    
    scp = explore_scatterplot(data = temp,
                              var1 = input$in_var1, 
                              var2 = input$in_var2)
  })
}

shinyApp(ui = ui, server = server)
0 Answers
Related