简体   繁体   English

为情节图例添加标题

[英]Add title to the plotly legend

In the following example how can i add a title to the legend in plot_ly for R ?在以下示例中,我如何为 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")

thanks谢谢

The only way I know is to use an annotation and add it to the plot.我知道的唯一方法是使用注释并将其添加到绘图中。 Like this:像这样:

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 )

Yielding:产量:

在此处输入图片说明

It is a bit tricky to place the legend title though, not sure if this placement would always work.不过放置图例标题有点棘手,不确定这个放置是否总是有效。

Another way would be to use ggplot and ggplotly of course, and let ggplot figure it out.另一种方法当然是使用 ggplot 和 ggplotly,然后让 ggplot 弄清楚。

This functionality has since been included within the layout function in the legend option.此功能已包含在legend选项的layout功能中。 There's a sub-option called title within which you can supply a list that includes the text.有一个名为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM