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

时间:2018-07-11 13:44:20

标签: r plotly subplot

我在R-Shiny应用程序中使用subplot函数从plotly绘制两个图(一个在另一个图下)。图例对于两个图形都是通用的,这意味着我只有一列,所有图例都组装在一起。

我想在子图中分别在每个图形附近放置图例。我如何获得它?

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)

The result of the above code

我想要的布局如下: The desired result

1 个答案:

答案 0 :(得分:1)

根据this,目前尚无法实现。这远非完美的破解方法,但如果您愿意,类似的方法可能是可行的-

使用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)

这将导致如下图所示。

enter image description here