指定图例标题的最简单方法是通过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 坐标用于标题和图例,但前者锚定在底部,而后者锚定在顶部。这样可以防止标题与图例“断开连接”。最终结果如下所示: