Skip to content

Instantly share code, notes, and snippets.

@AdamSpannbauer
Created January 12, 2018 19:15
Show Gist options
  • Save AdamSpannbauer/135793c68b90b46f44dbe50364c0edf5 to your computer and use it in GitHub Desktop.
Save AdamSpannbauer/135793c68b90b46f44dbe50364c0edf5 to your computer and use it in GitHub Desktop.
wordcloud2 example of click event and input resetting
#current preferred version of wc2
devtools::install_github("Lchiffon/wordcloud2#32")
#function to give wordcloud2 click interactivity
wc2ClickedWord = function(cloudOutputId, inputId) {
#ARGUMENTS
# - cloudOutputId: string; outputId of wordcloud2 obj being rendered (should be identical to the value passed to wordcloud2Output)
# - inputId: string; inputId of word clicked on (ie you will reference in server the word by input$inputId)
#OUPUT
# - referencing input in server will return a string of form word:freq (same as hover info shown in wordcloud; ie 'super:32')
shiny::tags$script(shiny::HTML(
sprintf("$(document).on('click', '#%s', function() {", cloudOutputId),
sprintf('word = document.getElementById("%swcSpan").innerHTML;', cloudOutputId),
sprintf("Shiny.onInputChange('%s', word);", inputId),
"});"
))
}
library(shiny)
library(wordcloud2)
shinyApp(
ui=shinyUI(fluidPage(
#custom message to null values
tags$script("
Shiny.addCustomMessageHandler('resetValue', function(variableName) {
Shiny.onInputChange(variableName, null);
});
"),
wordcloud2Output("my_wc"),
actionButton("clear_wc", label = "Clear WC1 Input"),
wordcloud2Output("my_wc2"),
actionButton("clear_wc2", label = "Clear WC2 Input"),
wc2ClickedWord("my_wc", "selected_word"),
wc2ClickedWord("my_wc2", "selected_word2"),
verbatimTextOutput("print"),
verbatimTextOutput("print2")
)),
server=shinyServer(function(input,output,session){
output$my_wc = renderWordcloud2(wordcloud2(demoFreq))
output$my_wc2 = renderWordcloud2(wordcloud2(demoFreq))
output$print = renderPrint(input$selected_word)
output$print2 = renderPrint(input$selected_word2)
#clear inputs on action button click
observeEvent(input$clear_wc, {
session$sendCustomMessage(type = "resetValue", message = "selected_word")
})
observeEvent(input$clear_wc2, {
session$sendCustomMessage(type = "resetValue", message = "selected_word2")
})
})
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment