在当前绘图中添加图层而不在ggplot2中创建新图层

时间:2015-08-30 22:34:12

标签: r ggplot2 shiny

在基本R中,您可以在不创建新图层的情况下将图层添加到现有图表中。

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

第二行创建绘图,第三行为现有绘图添加点。在ggplot2中:

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

第二行创建一个图,第三行创建另一个图。我可以以某种方式将点添加到第二行创建的现有绘图中吗?在ggplot中有类似add=TRUE的内容吗?

我想要这种行为的原因是在闪亮中使用ggplot2会导致其动画闪烁。

2 个答案:

答案 0 :(得分:3)

这是一个想法。将绘图保持为reactiveValue并让观察者使用用户输入更新绘图。然后,让另一个观察者观察绘图数据,该绘图数据将在绘图数据发生变化时渲染绘图。这样,长时间的计算就会在绘图数据发生变化之前发生,因此绘图的渲染应该很快发生,以至于应该有非常少的可见中断。以下是使用diamondggplot2数据集的示例,该数据集足够大,在渲染路径时显然很慢。

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
        ## })
    })
)

答案 1 :(得分:0)

我有完全相同的问题,我看到here使用特殊的css标签,它解决了问题,但实际上它并没有为我解决它。它可能对你有所帮助!

然而,我刚刚发现,您需要做的就是在ui chunck代码中添加此代码链接:tags$style(type="text/css", ".recalculating {opacity: 1.0;}")