1

I am trying to create plots using the following code from @blondeclover. The code is as follows -

library(shiny)
library(ggplot2)
library(plotly)
library(grid)

shinyApp(
    ##### ui #######
    ui = fluidPage(
        fluidRow(
            sliderInput("n", 
                        "Number of plots", 
                        value = 1, min = 1, max = 5)),
        fluidRow(
            plotlyOutput("plots")
        )
    ), 
    ##### server ######
    server = function(input, output) {
        data("cars")
        # define max number of plots
        max_plots <- 5
        # generate the plots
        output$plots <- renderPlotly({
            plot_list <- lapply(1:input$n, function(i) {
                g <- ggplot(cars, aes(x = speed, y = dist)) +
                    geom_point() +
                    theme(plot.margin = unit(c(3, 1, 1, 1), "lines"))
                ggplotly(g)
            })
            p <- subplot(plot_list[1:input$n], shareX = TRUE, shareY = TRUE) %>%
                layout(title = "Car Plots")
            dev.off()
            p
        })
    }
)

However, I am unable to bring up the title of each subplots I receive as output. My plot's title varies via a parameter. So, I want to display it as title. How to render title for each plot instead of a single title for all?

Naive_Natural2511
  • 687
  • 2
  • 8
  • 20

1 Answers1

0

I found the answer. We need to use facet_wrap instead of ggtitle in the ggplot code. Posting it here, so that it would be useful for anyone who stumble on the same issue as mine. Code is as follows:

library(shiny)
library(ggplot2)
library(plotly)
library(grid)

shinyApp(
    ##### ui #######
    ui = fluidPage(
        fluidRow(
            sliderInput("n", 
                        "Number of plots", 
                        value = 1, min = 1, max = 5)),
        fluidRow(
            plotlyOutput("plots")
        )
    ), 
    ##### server ######
    server = function(input, output) {
        data("cars")
        # define max number of plots
        max_plots <- 5
        cars$main1 <- "title"
        # generate the plots
        output$plots <- renderPlotly({
            plot_list <- lapply(1:input$n, function(i) {
                g <- ggplot(cars, aes(x = speed, y = dist)) +
                    geom_point() + 
                    facet_wrap(~main1) +
                    theme(plot.margin = unit(c(3, 1, 1, 1), "lines"))
                ggplotly(g)
            })
            p <- subplot(plot_list[1:input$n], shareX = TRUE, shareY = TRUE)
            dev.off()
            p
        })
    }
)
Naive_Natural2511
  • 687
  • 2
  • 8
  • 20