In R plotly subplot graph, how to show only one legend?

Malta picture Malta · Oct 9, 2016 · Viewed 11.5k times · Source

I have a basic subplot with two graphs, both have a legend by default, but I want to see only one of them.

I tried this :

require(plotly)
p1 <- plot_ly(data=iris,x=~Sepal.Length,y=~Sepal.Width,split=~Species) %>% layout(showlegend = FALSE)
p2 <-  plot_ly(data=iris,x=~Sepal.Length,y=~Sepal.Width,split=~Species) %>% layout(showlegend = TRUE)
subplot(p1,p2)
subplot(p2,p1)

But it doesn't work : it seems as if only one showlegend attribute was handled, so if I start with p1 I have two legend, if I start with p2 I have two.

Any ideas ?

Answer

rvezy picture rvezy · Dec 13, 2016

I'll give you two answers, a straight one, and one for better practice and posterity (which also helps to better understand the problem) :

  1. Straight answer:
    Try to add showlegend = FALSE within the plot_ly() function, not in the layout() one. If we look at the ?subplot documentation:

    layout options found later in the sequence of plots will override options found earlier in the sequence.

    In other words, the layout showlegend option is only taken from your last plot. But using showlegend option from the plot_ly() function will affect the trace itself, saving its behavior within your subplot. Your code would now be as follows:

    require(plotly)  
    p1 <- plot_ly(data=iris,x=~Sepal.Length,y=~Sepal.Width,split=~Species,showlegend = F)
    p2 <-  plot_ly(data=iris,x=~Sepal.Length,y=~Sepal.Width,split=~Species, showlegend = T)  
    subplot(p1,p2)
    
  2. Better practice under plotly 4.0 and above.
    Use the pipe operator %>% and the group_by() function instead of split, as follows:

    p1 <-
      iris%>%
      group_by(Species)%>%
      plot_ly(x=~Sepal.Length, color= ~Species)%>%
      add_markers(y= ~Sepal.Width)
    p2 <-
      iris%>%
      group_by(Species)%>%
      plot_ly(x=~Sepal.Length, color= ~Species)%>%
      add_markers(y= ~Sepal.Width, showlegend = F)
    subplot(p1,p2)
    

This practice allows you to better understand how traces works in plotly. You can see that the data is first grouped by Species, passed to the plot_ly() function -which initializes the plot- and then you specify your trace type (markers) to actually make the plot.
Writing your code like this is easier when you want to add or remove traces and their respective options, add a grouping variable, or split/summarize your table.