简体   繁体   中英

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

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:

在此处输入图片说明

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.

This functionality has since been included within the layout function in the legend option. There's a sub-option called title within which you can supply a list that includes the text.

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", 
         legend = list(title = list(text = "<b>Cylinders</b>"))) # TITLE HERE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM