Search code examples
rggplot2shinyggplotly

Update ggplotly plot's subtitle based on shiny widget inputs


I need to update the subtitle of the ggplotly() plot in my shiny app based on the shiny widget input. But when I try to put it inside the text, it is hidden.

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

ui <- fluidPage(
  fluidRow(
    
    shinyWidgets::checkboxGroupButtons(inputId = "intervals_A", label = "Bins:",
                                       choices = c("(0.0, 10.0]", "(10.0, 70.0]", "(70.0, 330.0]", "(330.0, inf]"), selected = c("(0.0, 10.0]", "(10.0, 70.0]", "(70.0, 330.0]", "(330.0, inf]"),  justified = TRUE, checkIcon = list(yes = icon("ok", lib = "glyphicon")))
  ),
  fluidRow(plotlyOutput("plot"))
)

server <- function(input, output) {
  output$plot<-renderPlotly({
    
    p <- ggplot(ToothGrowth, aes(x = factor(dose), y = len)) + 
      geom_boxplot()
    p <- p + labs(title = "Effect of Vitamin C on Tooth Growth",
                  subtitle = "Plot of length by dose"
                  )
    ggplotly(p)%>% 
      layout(title = list(text = paste0('Effect of Vitamin C on Tooth Growth"',
                                        '<br>',
                                        '<sup>',
                                        'Plot of length by'),paste0(input$intervals_A) ,paste0('interval','</sup>')))
  })
  
}

shinyApp(ui, server)

Solution

  • write a global paste as a wrapper. And to paste multiple selections I added comma for input$intervals_A

    library(shiny)
    library(plotly)
    library(ggplot2)
    
    ui <- fluidPage(
        fluidRow(
            
            shinyWidgets::checkboxGroupButtons(inputId = "intervals_A", label = "Bins:",
                                               choices = c("(0.0, 10.0]", "(10.0, 70.0]", "(70.0, 330.0]", "(330.0, inf]"), selected = c("(0.0, 10.0]", "(10.0, 70.0]", "(70.0, 330.0]", "(330.0, inf]"),  justified = TRUE, checkIcon = list(yes = icon("ok", lib = "glyphicon")))
        ),
        fluidRow(plotlyOutput("plot"))
    )
    
    server <- function(input, output) {
        output$plot<-renderPlotly({
            
            p <- ggplot(ToothGrowth, aes(x = factor(dose), y = len)) + 
                geom_boxplot()
            p <- p + labs(title = "Effect of Vitamin C on Tooth Growth",
                          subtitle = "Plot of length by dose"
            )
            ggplotly(p)%>% 
                layout(title = list(text = paste(paste0('Effect of Vitamin C on Tooth Growth"',
                                                  '<br>',
                                                  '<sup>',
                                                  'Plot of length by'),paste0(input$intervals_A,collapse = ',') ,paste0('interval','</sup>'))))
        })
        
    }
    
    shinyApp(ui, server)