Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Legend title in plotly

Tags:

r

shiny

plotly

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

like image 349
Poornima Avatar asked Jun 26 '16 00:06

Poornima


People also ask

How do you show legend in Plotly?

By default, Plotly chart with multiple traces shows legends automatically. If it has only one trace, it is not displayed automatically. To display, set showlegend parameter of Layout object to True.

How do you hide legend titles in Plotly?

Plotly Show Legend To disable the Legend, we can use the update_layout() function and set the showlegend parameter to false.

How do you add labels in Plotly?

As a general rule, there are two ways to add text labels to figures: Certain trace types, notably in the scatter family (e.g. scatter , scatter3d , scattergeo etc), support a text attribute, and can be displayed with or without markers. Standalone text annotations can be added to figures using fig.

How do you make a title bold in Plotly R?

One method for getting bold text is to change the font to Arial Black (or other bold font) which should be available on most systems. This method will scale a little easier to axes and other elements. Save this answer.


1 Answers

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:

enter image description here

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:

enter image description here

like image 111
Artem Sokolov Avatar answered Sep 21 '22 12:09

Artem Sokolov