Last active
June 13, 2018 12:08
-
-
Save AdamSpannbauer/d93af343214c09c0ee7ce035dcdee5e1 to your computer and use it in GitHub Desktop.
wordcloud2 browseURL click event
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## install PR of wordcloud2 that adds click events | |
# devtools::install_github("Lchiffon/wordcloud2#35") | |
library(shiny) | |
library(shinyjs) | |
library(wordcloud2) | |
# define dummy data to use in example | |
wordcloud_df = data.frame(word = c('bing', 'google'), | |
freq = c(1, 2), | |
url = c('https://www.bing.com/', | |
'https://www.google.com/'), | |
stringsAsFactors = FALSE) | |
# define js function for opening urls in new tab/window | |
js_code = " | |
shinyjs.browseURL = function(url) { | |
window.open(url,'_blank'); | |
} | |
" | |
shinyApp( | |
ui=shinyUI(fluidPage( | |
# set up shiny js to be able to call our browseURL function | |
useShinyjs(), | |
extendShinyjs(text = js_code, functions = 'browseURL'), | |
# output our wordcloud | |
wordcloud2Output("my_wc") | |
)), | |
server=shinyServer(function(input,output,session){ | |
# create our wordcloud | |
output$my_wc = renderWordcloud2(wordcloud2(wordcloud_df)) | |
# observe word cloud click event | |
observeEvent(input$my_wc_clicked, { | |
# subset url of interest | |
clicked_word = strsplit(input$my_wc_clicked, ':')[[1]][1] | |
clicked_url = wordcloud_df$url[wordcloud_df$word == clicked_word] | |
# navigate to clicked url | |
js$browseURL(clicked_url) | |
}) | |
}) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment