从 ggplot2 转换为 plotly 后激活或停用图例键时绘图缩小或扩展

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

在下面的 Shiny 应用程序中,当我双击图例键以激活或停用它们时,绘图会缩小或展开。 我不确定这是否是 plotlyshiny 中的错误。 感谢任何解决此问题的帮助。感谢阅读!

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)

reprex package (v2.0.1)

于 2021-09-06 创建

我跳过了闪亮的部分,因为这个问题在 pure plotly 中也很普遍。问题似乎是空字符串。您可以考虑提交错误报告。

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")))