Search code examples
rplotplotly

Add title to the plotly legend


In the following example how can i add a title to the legend in plot_ly for R ?

mtcars %>%   plot_ly(x = ~disp, y = ~mpg, color = ~factor(cyl), size = ~wt) %>%   add_markers(
    hoverinfo = "text",
    text = ~paste("Displacement = ", disp, "\nMiles Per Gallon = ", mpg)   ) %>%   layout(title ="Custom Hover Text")

thanks


Solution

  • The only way I know is to use an annotation and add it to the plot. Like this:

    legendtitle <- list(yref='paper',xref="paper",y=1.05,x=1.1, text="Cylinders",showarrow=F)
    
    mtcars %>%  plot_ly(x = ~disp, y = ~mpg, color = ~factor(cyl), size = ~wt) %>%   
      add_markers(  hoverinfo = "text",
                    text = ~paste("Displacement=",disp, "\nMiles Per Gallon = ", mpg)) %>%   
      layout(title ="Custom Hover Text", annotations=legendtitle )
    

    Yielding:

    enter image description here

    It is a bit tricky to place the legend title though, not sure if this placement would always work.

    Another way would be to use ggplot and ggplotly of course, and let ggplot figure it out.