情节中的图例标题图例、情节、标题

2023-09-06 07:03:11 作者:派大星的小海绵

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

How do I specify title for legend in plotly? I have a stacked bar graph that plots different durations like 0-10, 11-20. I want the legend title to say 'Duration'.

推荐答案

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

The simplest way to specify a legend title is to set it via ggplot and have plotly read it from the corresponding object:

library( plotly )

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

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

However, the problem is that plotly converts the legend title into an annotation, which becomes disconnected from the legend in the process. In my browser, it also overlaps with the plotly menus in the top right corner:

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

To get around this problem, you can remove the legend title from the ggplot object altogether and add the annotation by hand yourself:

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坐标,但前者锚定在底部,而后者锚定在顶部.这样可以防止标题与图例断开连接".最终结果如下所示:

Note that the same y coordinate is used for both the title and the legend, but the former is anchored at the bottom, while the latter is anchored at the top. This keeps the title from being "disconnected" from the legend. Here's what the final result looks like: