開始使用免費開始

探索各國料理:文字雲

希望你在打造這些美食主題的 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 建立網頁應用程式

檢視課程

練習說明

  • 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)
編輯並執行程式碼