Aan de slagGa gratis aan de slag

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
)

Deze oefening maakt deel uit van de cursus

Building Web Applications with Shiny in R

Cursus bekijken

Oefeninstructies

  • 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.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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)
Code bewerken en uitvoeren