2

I would like to stack vertically 2 plots in a shiny app and use plotly to make them interactive.

I have the following code:

library(shiny)
library(tidyverse)
library(patchwork)
library(plotly)

ui <- fluidPage(
  
  tabsetPanel(
    tabPanel('Plot', plotOutput('plot')), 
    tabPanel('Plot2', plotly::plotlyOutput('plot2')), 
    tabPanel('Plot3', plotly::plotlyOutput('plot3'))
  )
)

server <- function(input, output) {

    output$plot <- renderPlot({
      p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) + 
        geom_line()
      p2 <- ggplot(data = mtcars, aes(x = mpg, y = disp)) + 
        geom_line()
      p1 / p2
    })
    
    output$plot2 <- renderPlotly({
      p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) + 
        geom_line()
    })
    
    output$plot3 <- renderPlotly({
      p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) + 
        geom_line()
      p2 <- ggplot(data = mtcars, aes(x = mpg, y = disp)) +
        geom_line()
      p1 / p2
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

As you can see when only using ggplot2 with the patchwork package ("Plot") it works as intended and stacks p1 and p2 vertically. Additionally, in "Plot2" when only plotting p1 with ggplot2, it becomes interactive with plotly.

However, in "Plot3" when trying to convert the combined graph (p1 / p2) of "Plot" created with patchwork to interactive using plotly, it only plots the p2 graph as interactive.

Any suggestions on how to create vertically stacked graphs using ggplot2 and then make them interactive with plotly in a Shiny App?

0

1 Answer 1

1

In R plotly you can achive this via the subplot function:

library(shiny)
library(tidyverse)
library(patchwork)
library(plotly)

ui <- fluidPage(
  
  tabsetPanel(
    tabPanel('Plot', plotOutput('plot')), 
    tabPanel('Plot2', plotly::plotlyOutput('plot2')), 
    tabPanel('Plot3', plotly::plotlyOutput('plot3'))
  )
)

server <- function(input, output) {
  
  output$plot <- renderPlot({
    p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) + 
      geom_line()
    p2 <- ggplot(data = mtcars, aes(x = mpg, y = disp)) + 
      geom_line()
    p1 / p2
  })
  
  output$plot2 <- renderPlotly({
    p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) + 
      geom_line()
  })
  
  output$plot3 <- renderPlotly({
    p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) + 
      geom_line()
    p2 <- ggplot(data = mtcars, aes(x = mpg, y = disp)) +
      geom_line()
    subplot(p1, p2, nrows = 2)
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

Please see this for more information.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.