Home > Blockchain >  R shiny - combining ggplot2 and plotly to stack vertically 2 subplots
R shiny - combining ggplot2 and plotly to stack vertically 2 subplots

Time:02-11

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?

CodePudding user response:

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.

  • Related