Search code examples
rggplot2shinyplotlyggplotly

Plot shrank or expanded when activating or deactivating legend keys after converting from ggplot2 to plotly


In the Shiny app below, when I double-clicked on the legend keys to activate or deactive them, the plot shrank or expanded. I am not sure if this is a bug in either plotly or shiny. Appreciate any help to troubleshoot this. Thanks for reading!

library(ggplot2)
library(plotly)
library(shiny)

# ui
ui <- bootstrapPage(
  plotlyOutput('rev')
)

# server
server <- function(input, output) {
  output$rev <- renderPlotly({
    
    p <- ggplot(mpg, aes(x = displ, y = hwy, color = factor(cyl), shape = class)) +
      geom_point(size = 3) +
      scale_color_manual(values = c("4" = "#abd9e9",
                                    "5" = "#2c7bb6",
                                    "6" = "#ff7f00",
                                    "8" = "#d7191c")) +
      scale_shape_manual(values = c(2, 5, 16, 17, 18, 19, 25)) +
      guides(color = guide_legend(title = "Cyl", order = 1),
             shape = guide_legend(title = "", order = 2)) +
      theme_classic(base_size = 16)
    p
    
    ggplotly(p) %>% 
      # layout(autosize = FALSE) %>%                        # did not work
      layout(xaxis = list(autorange = "reversed", 
                          tickvals = c(2, 3, 5, 6),
                          ticktext = c("2", "", "5", "6")))
  })
}

# Return a Shiny app object
shinyApp(ui = ui, server = server)

Created on 2021-09-06 by the reprex package (v2.0.1)


Solution

  • I skipped the shiny part since the issue prevails with pure plotly as well. the issue seems to be the empty string. you can think about filing a bug report.

    p <- ggplot(mpg, aes(x = displ, y = hwy, color = factor(cyl), shape = class)) +
    geom_point(size = 3) +
        scale_color_manual(values = c("4" = "#abd9e9",
                                      "5" = "#2c7bb6",
                                      "6" = "#ff7f00",
                                      "8" = "#d7191c")) +
        scale_shape_manual(values = c(2, 5, 16, 17, 18, 19, 25)) +
        guides(color = guide_legend(title = "Cyl", order = 1),
               shape = guide_legend(title = "", order = 2)) +
        theme_classic(base_size = 16)
    p
    
    ggplotly(p) %>%
        layout(xaxis = list(autorange = "reversed",
                            tickvals = c(2, 3, 5, 6),
                            
                            # empty strings cause trouble, just include a space
                            ticktext = c("2", " ", "5", "6")))