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

后端 未结 4 1483
再見小時候
再見小時候 2020-12-06 11:09

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 <- pl         


        
4条回答
  •  感动是毒
    2020-12-06 11:27

    There seem to be some uncertain points in the answers given until now.

    First of all data frame grouping hasn't any influence as far as I can see it. It is a question of sorting not grouping (as Maltas comment above indicates). So the data frame must sorted by the variable which is intended to serve as grouping variable. But there is another pitfall which nevertheless prevents the code working. Besides the required legendgroup you have therefore to ensure

    1. that your data frame is sorted by your grouping variable (fortunately iris data are already sorted by Species),
    2. that the variables you are using don't contain missing values (NAs).

    Thus this should work:

    library(plotly)
    p1 <-
      iris %>%
      arrange(Species) %>%
      plot_ly(x = ~Sepal.Length, color = ~Species, legendgroup = ~Species) %>%
      add_markers(y = ~Sepal.Width)
    p2 <-
      iris %>%
      arrange(Species) %>%
      plot_ly(x = ~Sepal.Length, color = ~Species, legendgroup = ~Species) %>%
      add_markers(y= ~Sepal.Width, showlegend = FALSE)
    
    subplot(p1, p2)
    

    The following examples do not work:

    1. Sorted by wrong variable:

      p1 <-
        iris %>%
        arrange(Sepal.Length) %>%
        plot_ly(x = ~Sepal.Length, color = ~Species, legendgroup = ~Species) %>%
        add_markers(y = ~Sepal.Width)
      p2 <-
        iris%>%
        arrange(Sepal.Length) %>%
        plot_ly(x=~Sepal.Length, color= ~Species, legendgroup=~Species)%>%
        add_markers(y = ~Sepal.Width, showlegend = FALSE)
      
      subplot(p1, p2)
      
    2. Variables with missing values:

      df <- iris
      df$Sepal.Length[2] <- NA
      head(df)
      
      #>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
      #> 1          5.1         3.5          1.4         0.2  setosa
      #> 2           NA         3.0          1.4         0.2  setosa
      #> 3          4.7         3.2          1.3         0.2  setosa
      #> 4          4.6         3.1          1.5         0.2  setosa
      #> 5          5.0         3.6          1.4         0.2  setosa
      #> 6          5.4         3.9          1.7         0.4  setosa
      
      p1 <-
        df %>%
        arrange(Species) %>%
        plot_ly(x = ~Sepal.Length, color = ~Species, legendgroup = ~Species) %>%
        add_markers(y = ~Sepal.Width)
      p2 <-
       df %>%
        arrange(Species) %>%
        plot_ly(x = ~Sepal.Length, color = ~Species, legendgroup = ~Species)%>%
        add_markers(y = ~Sepal.Width, showlegend = FALSE)
      
      subplot(p1, p2)
      

提交回复
热议问题