是否可以使用wordcloud2在Shining中创建单击事件?

是否可以使用wordcloud2在Shining中创建单击事件?,r,shiny,word-cloud,R,Shiny,Word Cloud,wordcloud2软件包是否可以将wordcloud中任何单词的点击作为点击事件返回,以便将其他对象(如bsModal)绑定到它?例如,在plotly中,这是通过生成一个对象来实现的,该对象可以从shiny会话中访问并保存事件数据(例如,单击坐标)() 在下面的示例中,我希望将bsModal绑定到wordcloud,以便显示用户单击的单词 用户界面 服务器.R library(shiny) library(wordcloud2) library(tm) shinyServer(functio

wordcloud2软件包是否可以将wordcloud中任何单词的点击作为点击事件返回,以便将其他对象(如bsModal)绑定到它?例如,在plotly中,这是通过生成一个对象来实现的,该对象可以从shiny会话中访问并保存事件数据(例如,单击坐标)()

在下面的示例中,我希望将bsModal绑定到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)
})
库(闪亮)
图书馆(wordcloud2)
图书馆(tm)
shinyServer(功能(输入、输出){

words是的,您可以通过在闪亮应用程序的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\u word
访问该变量,并使用该变量将wordcloud与应用程序中的其他对象绑定

由于它接受悬停函数的值,因此输入的格式将为
word:freq
。您可以使用
gsub()
来去除频率和冒号,如下所示:
gsub(“:*”,“”,隔离(输入$selected_word))

希望有帮助

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