如何使图例出现在 plotly 上但不绘制关联点

How to make a legend appear on plotly but not plot the associated points

我有一个情节,我只想渲染图例,但 none 个情节点。谁能告诉我怎么做?

library(tidyverse)
library(plotly)

mtcars %>% 
  mutate(cyl = factor(cyl)) %>% 
  plot_ly() %>% 
  add_markers(x = ~mpg,
              y = ~hp,
              color = ~cyl,
              colors = c("4" = "red", "6" = "green", "8" = "blue"))

目前我有这个:

我要的是这个:

不确定这个结果有什么用,但您可以像这样禁用 legendclick:

编辑: 也可以不用 onRender

library(plotly)
mtcars %>% 
  mutate(cyl = factor(cyl)) %>% 
  plot_ly() %>% 
  add_markers(x = ~mpg,
              y = ~hp,
              color = ~cyl,
              colors = c("4" = "red", "6" = "green", "8" = "blue"), visible='legendonly') %>%
  layout(legend=list(itemclick = FALSE, itemdoubleclick = FALSE)) 

library(htmlwidgets)
library(plotly)

js <- c(
  "function(el, x){",
  "  el.on('plotly_legendclick', function() {",
  "    return false;",
  "  });",
  "  el.on('plotly_legenddoubleclick', function() {",
  "    return false;",
  "  });",
  "}")

mtcars %>% 
  mutate(cyl = factor(cyl)) %>% 
  plot_ly() %>% 
  add_markers(x = ~mpg,
              y = ~hp,
              color = ~cyl,
              colors = c("4" = "red", "6" = "green", "8" = "blue"), visible='legendonly') %>%
  onRender(js)