开始使用免费开始使用

添加交互式图形输出

与创建交互式表格类似,您可以使用 plotly 包把用 ggplot2 创建的静态图轻松转换为交互式图。要渲染交互式图,请使用 plotly::renderPlotly(),并通过 plotly::plotlyOutput() 显示。

请记住,与其他 render 函数相同,plotly::renderPlotly() 中的代码必须包裹在花括号 {} 中!

本练习是课程的一部分

使用 R 构建 Shiny Web 应用

查看课程

练习说明

  • 创建按性别和年份划分的前 10 个最流行姓名的交互式图形。将输出命名为 "plot_trendy_names",并使用函数 plot_trends() 生成该图。
  • 在 UI 中显示该图。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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)
编辑并运行代码