Plot (ggplot2)

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

library(shiny)
library(bslib)
library(ggplot2)
library(palmerpenguins)

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

server <- function(input, output) {
  output$plot <- renderPlot( 
    { 
      ggplot(data = penguins, aes(body_mass_g)) + 
        geom_histogram(bins = input$slider) 
    } 
  ) 
}

shinyApp(ui = ui, server = server)
library(shiny)
library(bslib)
library(ggplot2)
library(palmerpenguins)

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

server <- function(input, output) {
  output$plot <- renderPlot( 
    { 
      ggplot(data = penguins, aes(body_mass_g)) + 
        geom_histogram(bins = input$slider) 
    } 
  ) 
}

shinyApp(ui = ui, server = server)
No matching items

Relevant Functions

  • plotOutput
    plotOutput(outputId, width = "100%", height = "400px", click = NULL, dblclick = NULL, hover = NULL, brush = NULL, inline = FALSE, fill = !inline)

  • renderPlot
    renderPlot(expr, width = "auto", height = "auto", res = 72, ..., alt = NA, env = parent.frame(), quoted = FALSE, execOnResize = FALSE, outputArgs = list())

No matching items

Details

Follow these steps to display a ggplot2 plot in your app:

  1. Call plotOutput() 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 plotOutput() to a unique value.

  2. Optionally, use the height and width arguments to control the height and width of the plot.

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

  4. Pass renderPlot() a block of code, surrounded with {}. The code should return a ggplot2 object.

You can also use a plot as an input widget, collecting the locations of user clicks, double clicks, hovers, and brushes. To do this, follow the instructions provided for interactive plots.

Variations