【问题标题】:Legend near each plot in subplot plot_ly in RR中子图plot_ly中每个图附近的图例
【发布时间】:2018-12-19 14:10:54
【问题描述】:

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

我想要的布局如下:

【问题讨论】:

标签: r plotly subplot


【解决方案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)

这将导致如下图。

【讨论】:

    猜你喜欢
    • 2020-12-10
    • 2018-10-03
    • 2020-05-01
    • 2017-08-21
    • 2013-06-12
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 2016-09-14
    相关资源
    最近更新 更多