เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

Explore cuisines: wordclouds

Hope you are having fun building these foody Shiny apps! A handy way to visualize a lot of data is wordclouds. In this exercise, you will extend the Shiny app we built previously and add a new tab that displays the top distinctive ingredients as an interactive wordcloud.

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

We have already loaded the packages shiny, dplyr, ggplot2, plotly, and d3wordcloud. Here is a handy snippet to create a wordcloud.

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

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Building Web Applications with Shiny in R

ดูคอร์ส

คำแนะนำการฝึกหัด

  • UI: Add a d3wordcloudOutput() named wc_ingredients, and wrap it in a tabPanel(). This should be the first tabPanel() in your app.
  • Server: 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. You'll need to use the reactive expression rval_top_ingredients() to return a data frame of the top ingredients with recipe counts.

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

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)
แก้ไขและรันโค้ด