简体   繁体   English

传奇标题在剧情中

[英]Legend title in plotly

How do I specify title for legend in plotly ? 如何在图中指定图例的plotly I have a stacked bar graph that plots different durations like 0-10, 11-20. 我有一个堆积条形图,绘制不同的持续时间,如0-10,11-20。 I want the legend title to say 'Duration'. 我希望传奇标题能说'持续时间'。

The simplest way to specify a legend title is to set it via ggplot and have plotly read it from the corresponding object: 指定图例标题的最简单方法是通过ggplot设置它并从相应的对象中plotly

library( plotly )

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

However, the problem is that plotly converts the legend title into an annotation, which becomes disconnected from the legend in the process. 然而,问题是, plotly图例标题转换成一个注释,成为从在该过程图例断开。 In my browser, it also overlaps with the plotly menus in the top right corner: 在我的浏览器中,它还与右上角的plotly菜单重叠:

在此输入图像描述

To get around this problem, you can remove the legend title from the ggplot object altogether and add the annotation by hand yourself: 要解决此问题,您可以完全从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" ) )

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. 请注意,标题和图例使用相同的y坐标,但前者锚定在底部,而后者锚定在顶部。 This keeps the title from being "disconnected" from the legend. 这样可以防止标题与图例“断开连接”。 Here's what the final result looks like: 以下是最终结果:

在此输入图像描述

If you are referring to something like this where the legend is titled, and the subplot's titles are customized ... 如果您指的是标题为图例的类似内容,并且子图的标题是自定义的 ......

Create a trace. 创建跟踪。 In that trace, use the annotations attribute to add a name to your legend. 在该跟踪中,使用annotations属性为图例添加名称。 I'm able to add pieces of text to my graph wherever I want if I specify an x value, a y value, and set xref = 'paper' and yref = 'paper' . 如果我指定一个x值,一个y值,并设置xref = 'paper'yref = 'paper' ,我就可以在我想要的任何地方添加文本片段。

Here is a tutorial on how annotations can be used to your benefit: Constructing a customized x- and y- axis title . 这是一个关于如何使用注释来获益的教程: 构建自定义的x轴和y轴标题

You can read more about annotations . 您可以阅读有关注释的更多信息。 They are useful! 它们很有用!

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

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