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)Relevant Functions
-
plotlyOutput
plotlyOutput(outputId, width = "100%", height = "400px", inline = FALSE, reportTheme = TRUE, fill = !inline) -
renderPlotly
renderPlotly(expr, env = parent.frame(), quoted = FALSE)
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:
Install and load the
plotlypackage.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 theoutputIdargument ofplotlyOutput()to a unique value.Within the server function, call
renderPlotly()and save its output as an element of theoutputlist. Name the element after theoutputIdused above. For example,output$plot <- renderPlotly().plotlyOutput()will display the value of theoutputelement whose name matches itsoutputId.Pass
renderPlotly()a block of code, surrounded with{}. The code should return aplotly()object created withggplotly(). To create a plot withggplotly(), first create a plot withggplot2. Then, pass yourggplot2plot toggplotly().
For more information, see Server-side linking with shiny.