gpt4 book ai didi

r - 在 Shiny 的应用程序中缓存基本 ggplot 并允许动态修改图层(与 ggplot 等效的leafletProxy)

转载 作者:行者123 更新时间:2023-12-03 14:59:47 25 4
gpt4 key购买 nike

如果显示的基本数据集很大(下面的示例工作代码),则在 Shiny 的应用程序中向/从 ggplot 添加/删除图层可能需要一段时间。

问题是:

有没有办法缓存 ggplot(基本图)并添加/删除/修改额外(动态)图层,而无需在 Shiny 的应用程序中重做整个图?
也就是说,等效于用于传单 map 的 LeafletProxy() 的函数(参见 leaflet Rstudio webpage 中的工作示例)。

stackoverflow thread 中提出了一种可能的解决方法。 (下面示例中的选项 B),但是,它不会阻止 ggplot 重做整个绘图。

示例工作代码:

library(shiny)
library(ggplot2)

shinyApp(
shinyUI(
fluidPage(
sidebarLayout(
sidebarPanel(
checkboxInput("line", "Add line")
),
mainPanel(
plotOutput("plot")
)
)
)
),
shinyServer(function(input, output, session) {
data(diamonds)
vals <- reactiveValues(pdata=ggplot())

observeEvent(input$line, {
p <- ggplot(diamonds, aes(x=carat, y=depth)) + geom_point()
if (input$line){
lineData <- data.frame(x=c(1, 4), y = c(60, 75))
p <- p + geom_line(data = lineData, aes(x=x, y=y), color = "red")
}
vals$pdata <- p
})
# Option A ------
# output$plot <- renderPlot({
# vals$pdata
# })
#
# Option B ------
observeEvent(vals$pdata,{
output$plot <- renderPlot({
isolate(vals$pdata)
})
})

})
)

最佳答案

您始终可以只绘制两个图,然后使用条件来选择要显示的图。初始渲染很慢,但初始化后效果很好。

library(shiny)
library(ggplot2)

shinyApp(
shinyUI(
fluidPage(
sidebarLayout(
sidebarPanel(
checkboxInput("line", "Add line", value = TRUE)
),
mainPanel(
conditionalPanel(condition = 'input.line == false',
plotOutput("plot1"),
),
conditionalPanel(condition = 'input.line == true',
plotOutput("plot2"),
),
)
)
)
),
shinyServer(function(input, output, session) {
#data(diamonds)


# Option C -------
output$plot1 <- renderPlot({
ggplot(diamonds, aes(x=carat, y=depth)) + geom_point()
})
output$plot2 <- renderPlot({
lineData <- data.frame(x=c(1, 4), y = c(60, 75))

ggplot(diamonds, aes(x=carat, y=depth)) +
geom_point()+
geom_line(data = lineData, aes(x=x, y=y), color = "red")
})

})
)

关于r - 在 Shiny 的应用程序中缓存基本 ggplot 并允许动态修改图层(与 ggplot 等效的leafletProxy),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39613464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com