为情节图例添加标题

Add title to the plotly legend

在下面的示例中,我如何为 R 的 plot_ly 中的图例添加标题?

mtcars %>%   plot_ly(x = ~disp, y = ~mpg, color = ~factor(cyl), size = ~wt) %>%   add_markers(
    hoverinfo = "text",
    text = ~paste("Displacement = ", disp, "\nMiles Per Gallon = ", mpg)   ) %>%   layout(title ="Custom Hover Text")

谢谢

我知道的唯一方法是使用注释并将其添加到图中。像这样:

legendtitle <- list(yref='paper',xref="paper",y=1.05,x=1.1, text="Cylinders",showarrow=F)

mtcars %>%  plot_ly(x = ~disp, y = ~mpg, color = ~factor(cyl), size = ~wt) %>%   
  add_markers(  hoverinfo = "text",
                text = ~paste("Displacement=",disp, "\nMiles Per Gallon = ", mpg)) %>%   
  layout(title ="Custom Hover Text", annotations=legendtitle )

产量:

虽然放置图例标题有点棘手,但不确定这种放置是否总是有效。

另一种方法当然是使用 ggplot 和 ggplotly,然后让 ggplot 自己解决。

此功能已包含在 legend 选项的 layout 功能中。有一个名为 title 的子选项,您可以在其中提供包含文本的列表。

mtcars %>% 
  plot_ly(x = ~disp, y = ~mpg, color = ~factor(cyl), size = ~wt) %>% 
  add_markers(hoverinfo = "text",
              text = ~paste("Displacement = ", disp, "\nMiles Per Gallon = ", mpg)   ) %>% 
  layout(title = "Custom Hover Text", 
         legend = list(title = list(text = "<b>Cylinders</b>"))) # TITLE HERE