Plot (plotly)

#| standalone: true
#| components: [viewer]
#| viewerHeight: 500

library(shiny)
library(bslib)
library(plotly)
library(palmerpenguins)
library(dplyr)

ui <- page_fluid(
  sliderInput(
    "slider",
    label = "Number of bins",
    min = 10,
    max = 60,
    value = 20
  ),
  plotlyOutput(outputId = "plot") 
)

server <- function(input, output, ...) {
  output$plot <- renderPlotly({ 
    p <- 
      penguins |> 
      filter(!is.na(body_mass_g)) |> 
      ggplot(aes(body_mass_g)) + 
      geom_histogram(bins = input$slider) 

    ggplotly(p) 
  }) 
}

shinyApp(ui, server)
library(shiny)
library(bslib)
library(plotly)
library(palmerpenguins)
library(dplyr)

ui <- page_fluid(
  sliderInput(
    "slider",
    label = "Number of bins",
    min = 10,
    max = 60,
    value = 20
  ),
  plotlyOutput(outputId = "plot") 
)

server <- function(input, output, ...) {
  output$plot <- renderPlotly({ 
    p <- 
      penguins |> 
      filter(!is.na(body_mass_g)) |> 
      ggplot(aes(body_mass_g)) + 
      geom_histogram(bins = input$slider) 

    ggplotly(p) 
  }) 
}

shinyApp(ui, server)
No matching items

Relevant Functions

  • plotlyOutput
    plotlyOutput(outputId, width = "100%", height = "400px", inline = FALSE, reportTheme = TRUE, fill = !inline)

  • renderPlotly
    renderPlotly(expr, env = parent.frame(), quoted = FALSE)

No matching items

Details

Plotly is an interactive graphics plotting library. You can use plotly::ggplotly() to convert a ggplot2::ggplot() object to a plotly object.

To make an interactive plot with Plotly in Shiny, we will need to use the plotly package.

Follow these steps to display a plotly::ggplotly() figure in your app:

  1. Install and load the plotly package.

  2. Call plotlyOutput() in the UI of your app to create a div in which to display the plot. Where you call this function within the UI functions will determine where the image will appear within the layout of the app. Set the outputId argument of plotlyOutput() to a unique value.

  3. Within the server function, call renderPlotly() and save its output as an element of the output list. Name the element after the outputId used above. For example, output$plot <- renderPlotly(). plotlyOutput() will display the value of the output element whose name matches its outputId.

  4. Pass renderPlotly() a block of code, surrounded with {}. The code should return a plotly() object created with ggplotly(). To create a plot with ggplotly(), first create a plot with ggplot2. Then, pass your ggplot2 plot to ggplotly().

For more information, see Server-side linking with shiny.