Adding / removing layers to / from ggplot in a brilliant application may take some time if the underlying dataset shown is large (working code example below).
The question arises:
Is there a way to cache ggplot (the base graph) and add / remove / change additional (dynamic) layers without redoing the whole plot in a brilliant application? That is, the function equivalent to leafletProxy () for booklet cards (see the working example in the leaflet of the Rstudio web page ).
A possible workaround is proposed in this stackoverflow (option B in the example below), however it does not prevent ggplot from redrawing the entire chart.
Example working code:
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
})
observeEvent(vals$pdata,{
output$plot <- renderPlot({
isolate(vals$pdata)
})
})
})
)
source
share