Add interactive plot output
Similar to creating interactive tables, you can easily turn a static plot created using ggplot2
into an interactive plot using the plotly
package. To render an interactive plot, use plotly::renderPlotly()
, and display it using plotly::plotlyOutput()
.
Remember that just like with other render functions, the code inside plotly::renderPlotly()
should be wrapped in curly braces {}
!
This exercise is part of the course
Building Web Applications with Shiny in R
Exercise instructions
- Create an interactive plot of the top 10 most popular names by sex and year. Name the output
"plot_trendy_names"
and use the functionplot_trends()
to generate the plot. - Display the plot in the UI.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
ui <- fluidPage(
selectInput('name', 'Select Name', top_trendy_names$name)
# CODE BELOW: Add a plotly output named 'plot_trendy_names'
)
server <- function(input, output, session){
# Function to plot trends in a name
plot_trends <- function(){
babynames %>%
filter(name == input$name) %>%
ggplot(aes(x = year, y = n)) +
geom_col()
}
# CODE BELOW: Render a plotly output named 'plot_trendy_names'
}
shinyApp(ui = ui, server = server)