【问题标题】:Add title to the plotly legend为情节图例添加标题
【发布时间】:2016-10-12 14:41:16
【问题描述】:

在以下示例中,我如何为 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")

谢谢

【问题讨论】:

    标签: r plot plotly


    【解决方案1】:

    此功能已包含在layout 函数的legend 选项中。有一个名为 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
    

    【讨论】:

    • 很奇怪,当颜色不离散时,这似乎不起作用。比如color = ~drat
    【解决方案2】:

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

    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 弄清楚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-28
      • 2021-02-15
      • 1970-01-01
      • 2015-03-30
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      • 2021-04-14
      相关资源
      最近更新 更多