[英]R/shiny: render elements of plots only when needed in shiny apps
我目前正在編寫一個閃亮的應用程序。 我想減少繪圖的渲染時間(因為初始化繪圖需要很長時間)。 假設我要動態繪制圖,例如
plot(x=1:10)
( plot
將不是我將在閃亮的應用程序中使用的功能。)
現在,我想將繪圖分為以下幾個部分:
plot(x=NA, y=NA, xlim=c(0,10), ylim=c(0,10))
points(x=1:10)
其中plot(x=NA, y=NA, xlim=c(0,10), ylim=c(0,10))
將在閃亮的應用程序中花費很長時間進行渲染並points(x=1:10)
將花費很短的時間。 我需要一個僅在首次加載應用程序時才會執行plot(x=NA, y=NA, xlim=c(0,10), ylim=c(0,10))
自底向上構建(將點,線等添加到繪圖中)。 有沒有人知道如何將其寫入應用程序? 這里的問題是,我將在閃亮的應用程序中使用的繪圖功能不會返回任何內容。 繪圖功能基於基本graphics
系統(不在ggplot2
,不在lattice
)。
這是此類應用程序的最小工作示例:
library(shiny)
shinyAPP <- function() {
ui <- fluidPage(
sidebarPanel(),
mainPanel(
plotOutput("plotPoints"))
)
server <- function(input, output, session) {
output$plotPoints <- renderPlot(
plot(x=1:10)
## this needs to be replaced with:
##plot(x=NA, y=NA, xlim=c(0,10), ylim=c(0,10))
##points(x=1:10)
)
}
app <- list(ui = ui, server = server)
runApp(app)
}
shinyAPP()
非常感謝你!
因此,也許像下面這樣嘗試grDevices
:
server.R:
library("shiny")
library("grDevices")
data(iris)
plot(x=NA, y=NA, xlim=c(0,10), ylim=c(0,10))
p <- recordPlot()
function(input, output, session) {
output$plotPoints <- renderPlot({
replayPlot(p)
points(1:input$ile)
})
}
和ui.R:
library(shiny)
fluidPage(
sidebarPanel(
sliderInput("ile", min=1, max=10, label="", value=5)
),
mainPanel(
plotOutput("plotPoints"))
)
您說過不會使用plot
,但是要使用的內容很重要。 例如,對於ggplot
你可以像這里(見reactive
):
ui.R:
library(shiny)
fluidPage(
sidebarPanel(
sliderInput("ile", min=1, max=10, label="", value=5)
),
mainPanel(
plotOutput("plotPoints"))
)
服務器
library("shiny")
library("ggplot2")
data(iris)
function(input, output, session) {
wyk <- reactive({ggplot(iris)})
output$plotPoints <- renderPlot(
wyk() + geom_point(aes(x=Sepal.Length, y=Sepal.Width), col=input$ile)
)
}
如果我理解您的問題,這是一個應該起作用的小技巧。 但是,這不是R't,只是一個快速修復。
測試/ui.R:
fluidPage(
sidebarPanel(
actionButton("trickButton","Useless"),
sliderInput("something", min=1, max=5, label="Useful", value=5)
),
mainPanel(
plotOutput("plotPoints")
)
)
測試/服務器R:
data(iris)
myData <<- NULL
superHeavyLoad <- function() {
print("That is super heavy !")
myData <<- iris
}
function(input, output, session) {
observe({
if (!input$trickButton)
superHeavyLoad()
})
output$plotPoints <- renderPlot(
plot(myData[,1:as.numeric(input$something)])
)
}
現在,在您的R控制台上:
require(shiny)
runApp("test")
Listening on http://127.0.0.1:7175
[1] "That is super heavy !"
而且,無論您做什么,都將永遠不會再更新超重零件。 現在,據我了解,您所做的就是將處理分為重一次性函數和反應性事情。 這是一種(不是很漂亮)的方式;-)
關於它的工作原理:全部在我們添加的按鈕中。 每當我們與按鈕交互時,以及在服務器啟動時,都會調用observe
函數。 if(!input$trickButton)
指出我們只是在服務器啟動時運行代碼(因為按鈕沒有值)。 您還可以使用renderUI
機制隱藏此無用的按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.