R 中子图 plot_ly 中每个图附近的图例

Legend near each plot in subplot plot_ly in R

我使用 plotly 的 subplot 函数在我的 R-shiny 应用程序中绘制两个图形(一个在另一个下面)。两个图的图例都很常见,这意味着我只有一列将所有图例组合在一起。

我想在子图中的每个图形附近分别显示图例。我怎样才能得到它?

p1 <-
 iris%>%
 group_by(Species)%>%
 plot_ly(x=~Sepal.Length, color= ~Species, legendgroup=~Species)%>%
 add_markers(y= ~Sepal.Width)
p2 <-
 iris%>%
 group_by(Species)%>%
 plot_ly(x=~Sepal.Length, color= ~Species, legendgroup=~Species)%>%
 add_markers(y= ~Sepal.Width)

 subplot(p1,p2, nrows = 2, shareX = T, shareY = F, titleX = T, titleY = T)

我想要的布局如下:

根据 this,目前还无法实现。这远非完美的 hack,但如果你愿意,这样的事情可能是可行的 -

使用 n 确定着色变量中唯一元素的数量。

library(plotly)
n <- 3L
clrs <- colorRampPalette(
  c(rgb(r = 198, g = 89, b = 17, maxColorValue = 255), '#267dff', 'black')
)(n)
annotations <- c('setosa', 'versicolor', 'virginica')
y_annotation <- seq(0.4, 0.6, length.out = n)
p1 <-
  iris %>%
  group_by(Species) %>%
  plot_ly(x = ~Sepal.Length, color = ~Species, showlegend = FALSE, colors = clrs) %>%
  add_markers(y= ~Sepal.Width) %>%
  layout(margin = list(r = 100))
for (i in seq_along(annotations)) {
  p1 <- add_annotations(
    p = p1, text = annotations[i], font = list(color = clrs[i]), 
    x = 1.05, y = y_annotation[i], xref = 'paper', yref = 'paper', 
    showarrow = FALSE, xanchor = 'left'
  )
}
p2 <-
  iris%>%
  group_by(Species) %>%
  plot_ly(x = ~Sepal.Length, color = ~Species, showlegend = FALSE, colors = clrs) %>%
  add_markers(y = ~Sepal.Width) %>%
  layout(margin = list(r = 100))
for (i in seq_along(annotations)) {
  p2 <- add_annotations(
    p = p2, text = annotations[i], font = list(color = clrs[i]), 
    x = 1.05, y = y_annotation[i], xref = 'paper', yref = 'paper', 
    showarrow = FALSE, xanchor = 'left'
  )
}
subplot(p1, p2, nrows = 2, shareX = T, shareY = F, titleX = T, titleY = T)

这将导致如下图所示。