探索各國料理:文字雲
希望你在打造這些美食主題的 Shiny 應用程式時玩得開心!要視覺化大量資料,一個很好用的方法是文字雲。這個練習中,你會延伸先前建立的 Shiny 應用程式,新增一個分頁,將最具代表性的食材以可互動的文字雲呈現。

我們已經載入 shiny、dplyr、ggplot2、plotly 和 d3wordcloud 套件。以下是建立文字雲的範例程式片段。
d3wordcloud(
words = c('hello', 'world', 'good'),
freqs = c(20, 40, 30),
tooltip = TRUE
)
本練習屬於課程
使用 R 的 Shiny 建立網頁應用程式
練習說明
- UI:新增一個名為
wc_ingredients的d3wordcloudOutput(),並將它包在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)