Skip to content

Instantly share code, notes, and snippets.

@prise6
Last active March 2, 2018 19:47
Show Gist options
  • Save prise6/afa56434c23d3c9501cb79d43945e3cd to your computer and use it in GitHub Desktop.
Save prise6/afa56434c23d3c9501cb79d43945e3cd to your computer and use it in GitHub Desktop.
Quick solution to make a googlevis sankey responsive with Shiny
# ------------------------------
# SANKEY WITH GOOGLE VIS
# PSEUDO RESPONSIVE
# ------------------------------
# librairies
library(googleVis)
library(shiny)
# datas
datSK <- data.frame(From=c(rep("A",3), rep("B", 3)),
To=c(rep(c("X", "Y", "Z"),2)),
Weight=c(5,7,6,2,9,4))
# variables
ratio = 0.3
# App
server <- function(input, output) {
getContainerDimension = reactive({
dimensions = list(
width = paste0(input$containerGvis, "px"),
height = paste0(input$containerGvis*ratio, "px")
)
if(is.null(input$containerGvis)){
dimensions$width = "automatic"
dimensions$height = "200px"
}
return(dimensions)
})
getSankey = eventReactive(input$containerGvis, {
gvisSankey(
datSK,
from = "From",
to = "To",
weight = "Weight",
options = list(
width = getContainerDimension()$width,
height = getContainerDimension()$height,
sankey = "{link: {color: { fill: '#d799ae' } },
node: { color: { fill: '#a61d4c' },
label: { color: '#871b47' } }}"))
}, ignoreNULL = TRUE)
output$gvis = renderGvis(
getSankey()
)
}
ui <- fluidPage(
fluidRow(
column(
width = 12,
tags$div(
id = "container-gvis",
htmlOutput("gvis", container = tags$div)
)
),
tags$script(type = "text/javascript", '
$(document).on("shiny:connected", function(event) {
Shiny.onInputChange("containerGvis", $("#container-gvis").innerWidth());
});
$(window).resize(function() {
waitForFinalEvent(function(){
var width = $("#container-gvis").innerWidth();
console.log(width);
Shiny.onInputChange("containerGvis", width);
}, 250, "idContainerGvis");
});
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
')
)
)
shinyApp(ui = ui, server = server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment