前进
请先查看@SBista 的帖子。
我只是想为一个特殊用例添加到该响应中:降低 Shiny 尝试重新渲染可视化的频率,因为通过用鼠标抓住窗口的一个边缘并以这种方式调整大小来缓慢调整窗口的大小. 对我来说,渲染时间需要一段时间,而且如果没有这些额外的代码,它会从一个窗口大小调整中背靠背地进行多次重新渲染。
回答
在我的里面我ui.R
有一个tags$script
带有以下 JS 字符串:
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);
}
})
在我的server.R
文件中,我有我的 observable:
observeEvent(input$dimension,{
output$multi_indicator_facility <- renderPlotly({
plot.multi_indicator_facility(input)
})
在我拥有的另一个文件中plot.multi_indicator_facility()
,大致如下:
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)
也不要忘记包含htmlwidgets
使用 onRender 的库。
library('htmlwidgets') # <-- include this somewhere (e.g. server.R)