如何在 plotly 布局元素中包含悬停

How to include hover in a plotly layout element

我被以下 plotly example 困住了,我想利用它:

library(plotly)
p <- plot_ly(economics, x = ~date, y = ~uempmed, name = "unemployment")

# add shapes to the layout
p <- layout(p, title = 'Highlighting with Rectangles',
             shapes = list(
               list(type = "rect",
                    fillcolor = "blue", line = list(color = "blue"), opacity = 0.3,
                    x0 = "1980-01-01", x1 = "1985-01-01", xref = "x",
                    y0 = 4, y1 = 12.5, yref = "y"),
               list(type = "rect",
                 fillcolor = "blue", line = list(color = "blue"), opacity = 0.2,
                 x0 = "2000-01-01", x1 = "2005-01-01", xref = "x",
                 y0 = 4, y1 = 12.5, yref = "y")))

如何为这些矩形添加悬停信息?以下均无效:

layout(p, title = 'Highlighting with Rectangles',
            shapes = list(
              list(type = "rect",
                   fillcolor = "blue", line = list(color = "blue"), opacity = 0.3,
                   x0 = "1980-01-01", x1 = "1985-01-01", xref = "x", 

                   # text - hoverinfo pair
                   text = "hello", hoverinfo = "text",
                   y0 = 4, y1 = 12.5, yref = "y"),
              list(type = "rect",
                   fillcolor = "blue", line = list(color = "blue"), opacity = 0.2,
                   x0 = "2000-01-01", x1 = "2005-01-01", xref = "x", 

                   # hovertext
                   hovertext = "good bye",
                   y0 = 4, y1 = 12.5, yref = "y")))

有什么方法可以在 plotly 中绘制矩形并对它们应用悬停。不幸的是,至少据我所知,R 中没有 type = "rect" 或类似的东西。

您可以通过添加多边形而不是形状来实现。往下看;

library(plotly)

plot_ly() %>% 
  add_polygons(x=c(as.Date("1980-01-01"), as.Date("1980-01-01"), 
                   as.Date("1985-01-01"), as.Date("1985-01-01")),
               y=c(4, 12.5, 12.5, 4),
               line=list(width=0),
               fillcolor='rgba(255, 212, 96, 0.5)', inherit = FALSE,
               name = 'Hello') %>% 
  add_polygons(x=c(as.Date("2000-01-01"), as.Date("2000-01-01"), 
                   as.Date("2005-01-01"), as.Date("2005-01-01")),
               y=c(4, 12.5, 12.5, 4),
               line=list(width=0),
               fillcolor='rgba(255, 212, 96, 0.5)', inherit = FALSE,
               name = 'Bye') %>% 
  add_markers(data = economics, x = ~date, y = ~uempmed, name = "unemployment")