Search code examples
rplotlylegend

R+Plotly: Customize Legend Entries


I must be having trouble with less than a one liner, but have a look at the snippet below: I cannot the legend option to enter the text that I want in the legend as the name of the species (say, "foo1", "foo2", "foo3"). Notice that I do not want to change the original (iris in this case) dataset.

Any suggestion?

library(tidyverse)
library(plotly)


plot_ly(iris, x = ~Sepal.Length,
       y = ~Sepal.Width,
       type = 'scatter', color = ~Species,
                       symbol = ~Species,
       mode = 'markers')   %>%
   
 layout(legend=list(title=list(text='My title')))

       
  

Solution

  • Plotly considers legend names to be associated with each trace rather than with the legend itself. So redefining names has to occur on each trace. If you don't want to modify the original dataset, you'd have to filter it by Species and add the trace with the new name one at a time, with something like this:

    library(tidyverse)
    library(plotly)
    
    plot_ly(iris %>% filter(Species == "setosa"), 
            x = ~Sepal.Length,
            y = ~Sepal.Width,
            type = 'scatter', 
            color = ~Species,
            symbol = ~Species,
            mode = 'markers',
            name = "foo 1")   %>%
      add_trace(data = iris %>% filter(Species == "versicolor"),
                x = ~Sepal.Length,
                y = ~Sepal.Width,
                type = 'scatter', 
                color = ~Species,
                symbol = ~Species,
                mode = 'markers',
                name = "foo 2") %>% 
      add_trace(data = iris %>% filter(Species == "virginica"),
                x = ~Sepal.Length,
                y = ~Sepal.Width,
                type = 'scatter', 
                color = ~Species,
                symbol = ~Species,
                mode = 'markers',
                name = "foo 3") %>% 
      
      layout(legend=list(title=list(text='My title')))
    

    In a more complex case, it may be best to indeed modify the dataset itself or use a loop. A similar question about a more complex case is here: Manipulating legend text in R plotly and the reference documentation on plotly legend names is here: https://plotly.com/r/legend/#legend-names