【问题标题】:Is it possible to create a click-event in shiny with wordcloud2?是否可以使用 wordcloud2 创建闪亮的点击事件?
【发布时间】:2019-03-13 16:49:08
【问题描述】:

wordcloud2 包是否可以将 wordcloud 的任何单词的点击返回为闪亮的点击事件,以便将其他对象(例如 bsModal)绑定到它?例如,在 plotly 中,这是通过生成一个可以从闪亮会话中访问并保存事件数据(例如点击坐标)的对象来实现的 (https://plot.ly/r/shinyapp-linked-click/)。

在下面的示例中,我想将 bsModal 绑定到 wordcloud,以便显示用户单击的单词。

ui.R

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

服务器.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)
})

【问题讨论】:

    标签: r shiny word-cloud


    【解决方案1】:

    是的,您可以通过在 Shiny 应用的 UI 中添加几行 javascript 来解决问题。

    只需如下修改您的 UI:

    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);",
                   "});"
                ))
        )
    ))
    

    此代码生成一个新的输入变量,您可以在 shinyapp 的服务器端通过 input$selected_word 访问该变量,您可以使用该变量将 wordcloud 与应用内的其他对象绑定。

    由于它采用悬停函数的值,因此输入的格式为word:freq。可以使用gsub()去掉频率和冒号,如下:gsub(":.*","",isolate(input$selected_word))

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-29
      • 1970-01-01
      • 1970-01-01
      • 2014-08-30
      相关资源
      最近更新 更多