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)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())
Details
Follow these steps to display a ggplot2 plot in your app:
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 theoutputIdargument ofplotOutput()to a unique value.Optionally, use the
heightandwidtharguments to control the height and width of the plot.Within the server function, call
renderPlot()and save its output as an element of theoutputlist. Name the element after theoutputIdused above. For example,output$plot <- renderPlot().plotOutput()will display the value of theoutputelement whose name matches itsoutputId.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.