将 plotly 的子图功能与共享图例一起使用,让每个组在图例中只出现一次

Using plotly's subplot function with a shared legend, have each group appear only once in the legend

我有下图:

df1 <- data.frame(col1 = rep(LETTERS[1:3], each = 4), col2 = rnorm(12), col3 = runif(12), col4 = rep(c("Fred", "Bob"), each = 6))
df1_list <- split(df1, df1$col1)
colors <- setNames(c('red', 'blue'), c("Fred", "Bob"))
lapply(df1_list, function (arg1) {
  plotly::plot_ly(arg1, x = ~col2, y = ~col3, color = ~col4, colors = colors) %>%
    layout(showlegend = T)
}) %>%
  subplot()

图例显示每个人的名字两次。是否有一种高效的编程方式可以在图例中仅显示一次每个名称?

我建议通过 ggplot2 绕道而行的解决方案。希望这对您的目的有所帮助。

library(tidyverse)
library(plotly)
df1 <- data.frame(col1 = rep(LETTERS[1:3], each = 4), col2 = rnorm(12), col3 = runif(12), col4 = rep(c("Fred", "Bob"), each = 6))

p <- ggplot(df1, aes(col2, col3)) + geom_point(aes(color = col4)) + facet_wrap("col1")

plotly::ggplotly(p)