在当前绘图中添加一个图层而不在ggplot2中创建一个新图层 [英] adding a layer to the current plot without creating a new one in ggplot2

查看:201
本文介绍了在当前绘图中添加一个图层而不在ggplot2中创建一个新图层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在基本的R中,您可以将图层添加到现有的图中,而无需创建新的图。

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)

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

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()

第二行创建一个情节,第三行创建另一个情节。我可以以某种方式将点添加到由第二行创建的现有情节?在ggplot中是否存在类似于 add = TRUE 的情况?

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?

我想要这种行为的原因是,使用ggplot2导致其动画眨眼。

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

推荐答案

这是一个想法。将绘图保存为 reactiveValue ,并让观察者用用户输入更新绘图。然后,让另一位观察者观察绘图数据变化时将绘制绘图的绘图数据。通过这种方式,在绘图数据发生变化之前发生长时间的计算,因此绘图的绘制应该发生得如此之快以至于应该只有很少的可见中断。这是一个使用 ggplot2 diamond 数据集的示例,它足够大,在渲染路径时显然很慢。 (b

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

这篇关于在当前绘图中添加一个图层而不在ggplot2中创建一个新图层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆