【问题标题】:Legend title in plotly情节中的图例标题
【发布时间】:2016-10-28 07:22:59
【问题描述】:

如何在plotly 中指定图例的标题?我有一个堆积条形图,它绘制不同的持续时间,如 0-10、11-20。我希望图例标题显示“持续时间”。

【问题讨论】:

标签: r shiny plotly


【解决方案1】:

如果你指的是这样的东西the legend is titled, and the subplot's titles are customized...

创建跟踪。在该跟踪中,使用annotations 属性为您的图例添加名称。如果我指定x 值、y 值并设置xref = 'paper'yref = 'paper',我可以将文本片段添加到我想要的任何地方。

这里是一个关于如何使用注释为您带来好处的教程:Constructing a customized x- and y- axis title

您可以阅读有关annotations 的更多信息。它们很有用!

【讨论】:

    【解决方案2】:

    指定图例标题的最简单方法是通过ggplot 设置它并让plotly 从相应的对象中读取它:

    library( plotly )
    
    gg <- ggplot( mtcars, aes( x=mpg, y=wt, color=factor(vs) ) ) +
      geom_point() + labs( color = "MyTitle" )
    ggplotly( gg )
    

    但是,问题是plotly 将图例标题转换为注释,在此过程中与图例断开连接。在我的浏览器中,它也与右上角的plotly 菜单重叠:

    要解决这个问题,您可以完全从ggplot 对象中删除图例标题,然后自己手动添加注释:

    gg <- ggplot( mtcars, aes( x=mpg, y=wt, color=factor(vs) ) ) +
      geom_point() + theme( legend.title = element_blank() )
    ggplotly( gg ) %>%
      add_annotations( text="MyTitle", xref="paper", yref="paper",
                      x=1.02, xanchor="left",
                      y=0.8, yanchor="bottom",    # Same y as legend below
                      legendtitle=TRUE, showarrow=FALSE ) %>%
      layout( legend=list(y=0.8, yanchor="top" ) )
    

    请注意,相同的y 坐标用于标题和图例,但前者锚定在底部,而后者锚定在顶部。这样可以防止标题与图例“断开连接”。最终结果如下所示:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2021-11-03
      • 2021-12-26
      • 1970-01-01
      • 2014-10-21
      相关资源
      最近更新 更多