Foreward
Please see the post by @SBista first.
I simply want to add to that response for a special use case: to lower the frequency of times Shiny attempts to re-render a visualization as the window is slowly resized by grabbing one of the edges of the window with the mouse and resizing that way. For me, render time took awhile, and without this additional code, it was doing several re-renders back to back from just one window resize.
Answer
Inside my ui.R
I have a tags$script
with the following JS string:
console.log("INFO: Loaded ui.R custom JS.");
// VARS
const REFRESH_RATE_MIN_SECONDS = 1.5;
var dimension = [0, 0];
var notRecentlyRendered = true;
var midRender = false;
var timeNow = Date.now();
var lastRendered;
var nowDiffMs;
// METHODS
$(document).on("shiny:connected", function(e) {
dimension[0] = window.innerWidth;
dimension[1] = window.innerHeight;
Shiny.onInputChange("dimension", dimension);
})
$(window).resize(function(e) {
timeNow = Date.now();
firstRender = (typeof(lastRendered) === "undefined");
if (firstRender === true) {
nowDiffMs = timeNow - lastRendered;
refreshRateMinMs = REFRESH_RATE_MIN_SECONDS * 1000;
notRecentlyRendered = nowDiffMs > refreshRateMinMs;
}
if ((midRender === false) && (notRecentlyRendered === true)) {
console.log("INFO: Adjusting figure height.");
dimension[0] = window.innerWidth;
dimension[1] = window.innerHeight;
midRender = true;
Shiny.onInputChange("dimension", dimension);
}
})
In my server.R
file I have my observable:
observeEvent(input$dimension,{
output$multi_indicator_facility <- renderPlotly({
plot.multi_indicator_facility(input)
})
In another file where I have plot.multi_indicator_facility()
, which goes roughly as follows:
gg = ggplot(...) # ... = a lot of code
ggp = ggplotly(gg, height=figure.height) # I took figure.height from input$dimension
# More JS within R:
ggp = onRender(
ggp, '
function(el) {
console.log("Rendered.");
lastRendered = Date.now();
midRender = false;
}
')
return(ggp)
Also don't forget to include the htmlwidgets
lib to use onRender.
library('htmlwidgets') # <-- include this somewhere (e.g. server.R)
fluidPage()
? – Redheadshiny-plotly output height and width adjusted to the current window size
? Do you want it do occupy certain ratio of your screen size? – Sitrajs
would be to get the window size and pass it toggplotly
function. Refer to this link to get the window size. – SitrarenderPlotly
orplotlyOutput
options. The mentioned sources are not useful in my case. – Abbevillian