R Shiny: Repeated labels in legend for subplots

Viewed 57

In the legend, I want two plots to share "color1" and "color2" label. Is there a way to do this?

Note: The input value x determines two pairs of values, namely, y1, z1 and y2, z2. Y1 and y2 should share the same color, and z1 and z2 should share the same color.

enter image description here

library(plotly)

ui <- fluidPage(
  
  titlePanel("Hello Shiny!"),
  
  sidebarLayout(
    
    sidebarPanel(
      sliderInput("x", "Slider X", min = 3, max = 10, value = 6),
    ),
    
    mainPanel(
      plotlyOutput(outputId = "plots")
    )
  )
)

server <- function(input, output) {
  
  output$plots <- renderPlotly({
    
    x<- floor(runif( input$x, min=0, max=10))
    y1<- 2* x
    z1<- (x)^2
    y2<- 1.5* x
    z2<- sqrt(x)
    results <- as.data.frame(cbind(x,y1,z1,y2,z2))
    
    plot1 <- ggplot(data=results,aes(x=x))+
      geom_line(aes(y=y1, color="color1"))+
      geom_point(aes(y=y1, color="color1"))+
      geom_line(aes(y=z1, color ="color2"))+
      geom_point(aes(y=z1, color ="color2"))
    
    p1 <- ggplotly(plot1)
    
    plot2 <- ggplot(data=results, aes(x=x))+
      geom_line(aes(y=y2, color="color1"))+
      geom_point(aes(y=y2, color="color1"))+
      geom_line(aes(y=z2, color="color2"))+
      geom_point(aes(y=z2, color="color2"))
    
    p2 <- ggplotly(plot2)
    
    subplot(p1,p2,nrows = 1)
  })
}

shinyApp(ui, server)
1 Answers

We can use style(showlegend = FALSE) to hide the legenditems for one of the plots:

library(plotly)

ui <- fluidPage(titlePanel("Hello Shiny!"),
                sidebarLayout(sidebarPanel(
                  sliderInput(
                    "x",
                    "Slider X",
                    min = 3,
                    max = 10,
                    value = 6
                  ),
                ),
                mainPanel(plotlyOutput(outputId = "plots"))))

server <- function(input, output) {
  output$plots <- renderPlotly({
    x <- floor(runif(input$x, min = 0, max = 10))
    y1 <- 2 * x
    z1 <- (x) ^ 2
    y2 <- 1.5 * x
    z2 <- sqrt(x)
    results <- as.data.frame(cbind(x, y1, z1, y2, z2))
    
    plot1 <- ggplot(data = results, aes(x = x)) +
      geom_line(aes(y = y1, color = "color1")) +
      geom_point(aes(y = y1, color = "color1")) +
      geom_line(aes(y = z1, color = "color2")) +
      geom_point(aes(y = z1, color = "color2"))
    
    p1 <- ggplotly(plot1) %>% style(showlegend = FALSE)
    
    plot2 <- ggplot(data = results, aes(x = x)) +
      geom_line(aes(y = y2, color = "color1")) +
      geom_point(aes(y = y2, color = "color1")) +
      geom_line(aes(y = z2, color = "color2")) +
      geom_point(aes(y = z2, color = "color2"))
    
    p2 <- ggplotly(plot2)
    
    subplot(p1, p2, nrows = 1)
  })
}

shinyApp(ui, server)

result

Related