开始使用免费开始使用

探索菜系:词云

希望您在构建这些与美食相关的 Shiny 应用时玩得开心!当需要可视化大量数据时,词云非常实用。本练习中,您将扩展我们之前构建的 Shiny 应用,并新增一个选项卡,用交互式词云展示最具区分度的食材。

An app displaying an interactive wordcloud of top ingredients by chosen cuisine

我们已经加载了 shinydplyrggplot2plotlyd3wordcloud 包。下面是一段创建词云的便捷代码片段。

d3wordcloud(
  words = c('hello', 'world', 'good'), 
  freqs = c(20, 40, 30),
  tooltip = TRUE
)

本练习是课程的一部分

使用 R 构建 Shiny Web 应用

查看课程

练习说明

  • UI:添加名为 wc_ingredientsd3wordcloudOutput(),并将其包裹在一个 tabPanel() 中。它应当是应用中的第一个 tabPanel()
  • Server:使用 d3wordcloud::renderD3wordcloud() 渲染一个交互式词云,展示最常见食材以及它们被用于的配方数量,并将其赋给名为 wc_ingredients 的输出。您需要使用响应式表达式 rval_top_ingredients() 来返回包含最常见食材及配方计数的数据框。

交互式实操练习

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

ui <- fluidPage(
  titlePanel('Explore Cuisines'),
  sidebarLayout(
    sidebarPanel(
      selectInput('cuisine', 'Select Cuisine', unique(recipes$cuisine)),
      sliderInput('nb_ingredients', 'Select No. of Ingredients', 5, 100, 20),
    ),
    mainPanel(
      tabsetPanel(
        # CODE BELOW: Add `d3wordcloudOutput` named `wc_ingredients` in a `tabPanel`
        
        tabPanel('Plot', plotly::plotlyOutput('plot_top_ingredients')),
        tabPanel('Table', DT::DTOutput('dt_top_ingredients'))
      )
    )
  )
)

server <- function(input, output, session){
  # CODE BELOW: Render an interactive wordcloud of top ingredients and 
  # the number of recipes they get used in, using `d3wordcloud::renderD3wordcloud`,
  # and assign it to an output named `wc_ingredients`.
  
  
  
  
  rval_top_ingredients <- reactive({
    recipes_enriched %>% 
      filter(cuisine == input$cuisine) %>% 
      arrange(desc(tf_idf)) %>% 
      head(input$nb_ingredients) %>% 
      mutate(ingredient = forcats::fct_reorder(ingredient, tf_idf))
  })
  output$plot_top_ingredients <- plotly::renderPlotly({
    rval_top_ingredients() %>%
      ggplot(aes(x = ingredient, y = tf_idf)) +
      geom_col() +
      coord_flip()
  })
  output$dt_top_ingredients <- DT::renderDT({
    recipes %>% 
      filter(cuisine == input$cuisine) %>% 
      count(ingredient, name = 'nb_recipes') %>% 
      arrange(desc(nb_recipes)) %>% 
      head(input$nb_ingredients)
  })
}

shinyApp(ui = ui, server= server)
编辑并运行代码