Legend title in plotly

血红的双手。 提交于 2020-01-13 02:44:11

问题


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'.


回答1:


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:




回答2:


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. 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'.

Here is a tutorial on how annotations can be used to your benefit: Constructing a customized x- and y- axis title.

You can read more about annotations. They are useful!



来源:https://stackoverflow.com/questions/38034308/legend-title-in-plotly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!