图例中的图例标题 [英] Legend title in plotly
问题描述
如何在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:
这篇关于图例中的图例标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!