Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a click-event in shiny with wordcloud2?

Is it possible with the wordcloud2 package to return a click on any word of the wordcloud as a click event in shiny in order to bind other objects (e.g. bsModal) to it? For example, in plotly this is accomplished by generating an object that can be accessed from within the shiny session and holds the event data (e.g. click coordinates) (https://plot.ly/r/shinyapp-linked-click/).

In the example below, I would like to bind a bsModal to the wordcloud such that the word, on which the user has clicked, is displayed.

ui.R

library(shiny)
shinyUI(fluidPage(
    mainPanel(
        wordcloud2Output("wordcloud")
    )
))

server.R

library(shiny)
library(wordcloud2)
library(tm)

shinyServer(function(input, output) {

    words <- c ("1st", "2nd", "3rd", "4th", "5h", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th", "20th",
            "21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th", "30th")
    random_words <- sample(words, 500, replace = TRUE)
    docs <- Corpus(VectorSource(random_words))
    dtm <- TermDocumentMatrix(docs)
    m <- as.matrix(dtm)
    v <- sort(rowSums(m),decreasing=TRUE)
    d <- data.frame(word = names(v),freq=v)

    wordcloud_plot <- wordcloud2(data = d, size = 0.7, shuffle =FALSE, ellipticity = 1, minRotation = -pi/8, maxRotation = pi/8,
                            shape = 'circle')
    output$wordcloud  <- renderWordcloud2(wordcloud_plot)
})
like image 277
jas84 Avatar asked Jun 12 '17 15:06

jas84


1 Answers

Yes, you can have a workaround by adding few lines of javascript to the UI of the Shiny app.

Just modify your UI as follows:

library(shiny)
shinyUI(fluidPage(
    mainPanel(
        wordcloud2Output("wordcloud"),
        tags$script(HTML(
               "$(document).on('click', '#canvas', function() {",
               'word = document.getElementById("wcSpan").innerHTML;',
               "Shiny.onInputChange('selected_word', word);",
               "});"
            ))
    )
))

This code generates a new input variable that you can access via input$selected_word in the server side of the shinyapp, and that you can use to bind the wordcloud with other objects within the app.

As it takes the value of the hover function, the input will have the format word:freq. You can use gsub() to get rid of the frequency and colon as follows: gsub(":.*","",isolate(input$selected_word))

Hope it helps!

like image 154
arabinelli Avatar answered Sep 27 '22 23:09

arabinelli