Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

r - adding a layer to the current plot without creating a new one in ggplot2

In basic R you can add layers to the existing plot without creating a new one.

df <- data.frame(x = 1:10, y = runif(10))
plot(df, type = "l")
points(df, add = T)

The second line creates a plot and the third line adds points to the existing plot. In ggplot2:

my_plot <- ggplot(df, aes(x, y)) + geom_path()
my_plot
my_plot + geom_point()

The second line creates a plot and the third one creates another plot. Can I somehow add the points to the existing plot created by the second line? Is there something like add=TRUE in ggplot?

The reason I want this behaviour is that using ggplot2 in shiny causes blinks in its animations.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is an idea. Keep the plot as a reactiveValue and have an observer to update the plot with user inputs. Then, have another observer to watch the plot data that will render the plot when the plot data changes. This way the long calculations happen before the plot data is changed, so the rendering of the plot should happen so quickly that there should be very little visible interrupt. Here is an example using the diamond dataset from ggplot2 which is large enough to be obviously slow when rendering paths.

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

        observe({
            input$x; input$y; input$line
            p <- ggplot(diamonds, aes_string(input$x, input$y)) + geom_point()
            if (input$line)
                p <- p + geom_line(aes(group=cut))
            vals$pdata <- p
        })

        observeEvent(vals$pdata,{ 
            output$plot <- renderPlot({
                isolate(vals$pdata)
            })
        })
        ## Compare to this version
        ## output$plot <- renderPlot({
        ##     vals$pdata
        ## })
    })
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...