首页 > 解决方案 > R Plotly禁用图例单击和图例双击

问题描述

我想使用 R Plotly 从服务器端禁用情节图例选择。我们在这里看到,可以使用以下方法在 plotly javascript 上实现这一点,

gd.on('plotly_legendclick',function() { return false; })

有什么方法可以在 R 中使用event_register()or来实现这一点event_data()

我找到了一个使用 CSS 禁用图例的 hacky 解决方案。但是,如果您有多个不同的图output$gg,则 CSS 代码会禁用所有图的图例。

代表:

最终目标,点击下面的图例一定不能隐藏任何点。

library(shiny)
library(plotly)
library(tidyverse)

ui <- fluidPage(
  plotlyOutput("gg"),
  verbatimTextOutput("click"),
  verbatimTextOutput("doubleclick")
)

server <- function(input, output, session) {

  output$gg <- renderPlotly({
    p <- ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
      geom_point() + 
      facet_wrap(~vs)
    ggplotly(p) %>%
      event_register("plotly_legendclick") %>%
      event_register("plotly_legenddoubleclick")
  })

  output$click <- renderPrint({
    event_data("plotly_legendclick")
  })

  output$doubleclick <- renderPrint({
    event_data("plotly_legenddoubleclick")
  })
}

shinyApp(ui,server)

标签: rggplot2shinyplotlyr-plotly

解决方案


这是一份工作htmlwidgets::onRender

library(plotly)
library(htmlwidgets)

x <- c(1:15)
y <- c(1:15)
w <- gl(3,5)
dat <- data.frame(x = x, y = y, w = w)
example <- ggplot(dat, aes(x = x, y = y, color = w)) + geom_line()

ggplotly(example) %>% 
  onRender("function(el,x){el.on('plotly_legendclick', function(){ return false; })}")

推荐阅读