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 )
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:
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" ) )
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:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…