2017-06-12 72 views
1

使用wordcloud2軟件包可以將wordcloud的任何單詞作爲點擊事件閃爍以便將其他對象綁定到它(例如bsModal)嗎?例如,通過生成可以從閃亮會話內訪問並保存事件數據(例如,點擊座標)的對象(https://plot.ly/r/shinyapp-linked-click/)來示意性地實現這一點。是否有可能用wordcloud2創建閃亮的點擊事件?

在下面的示例中,我想將bsModal綁定到wordcloud,以便顯示用戶單擊的單詞。

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) 
}) 

回答

3

是的,你可以有通過添加JavaScript的幾行,以閃亮的應用程序的UI一種解決方法。

只需修改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))

希望它有幫助!

相關問題