代码之家  ›  专栏  ›  技术社区  ›  Jac

使用循环更新ggplot2折线图的数据

  •  2
  • Jac  · 技术社区  · 7 年前

    嗨,我是编程新手,还有“R”。编写了以下代码来测试ping连续性:

    library(pingr)
    library(ggplot2)
    
    cc=2
    counts <- c(1:1)
    pings <- c(ping("8.8.8.8",count = 1))
    
    rgh <- data.frame(counts,pings)
    ggplot(rgh, aes(x=counts,y=pings))+geom_line(aes(col="red"))+coord_cartesian(xlim=(c(0,300)),ylim=(c(0,100)))
    #qplot(x=counts,y=pings,data=rgh)
    
    while (cc<300) {
      counts <- c(counts,cc)
      pings <- c(pings,ping("8.8.8.8",count = 1))
    
      rgh <- data.frame(counts,pings)
        print(ggplot(rgh, aes(x=counts,y=pings))+geom_line(aes(col="red"))+coord_cartesian(xlim=(c(0,300)),ylim=(c(0,100))))
        cc <- cc+1
    
    }
    

    我想让它看起来像速度测试时的酷图表。网但这一次每次循环都会重新绘制整个情节,这需要太多时间。还有别的办法吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   missuse    7 年前

    下面是一个示例,介绍如何使用shiny和plotly设置所需的行为:

    library(shiny)
    library(plotly)
    library(pingr) 
    

    带有开始按钮和绘图区域的简单ui:

    ui <- fluidPage(
      div(actionButton("button", "start")),
      div(plotlyOutput("plot"), id='graph')
    )
    
    server <- function(input, output, session) {
      p <- plot_ly(
        y = ping("8.8.8.8",count = 1),
        type = 'scatter',
        mode = 'lines') 
      output$plot <- renderPlotly(p)
      observeEvent(input$button, {
        while(TRUE){
          Sys.sleep(1)
          plotlyProxy("plot", session) %>%
            plotlyProxyInvoke("extendTraces", list(y=list(list(ping("8.8.8.8",count = 1)))), list(0))
        }
      })
    }
    
    shinyApp(ui, server)
    

    过了一段时间,它看起来是这样的:

    enter image description here

    编辑:评论中问题的答案: 有多种方法可以控制ping的数量。也许是最简单的:

    server <- function(input, output, session) {
      p <- plot_ly(
        y = ping("8.8.8.8",count = 1),
        type = 'scatter',
        mode = 'lines') 
      a = 1
      output$plot <- renderPlotly(p)
      observeEvent(input$button, {
        while(a <= 30){
          a <- a + 1
          Sys.sleep(1)
          plotlyProxy("plot", session) %>%
            plotlyProxyInvoke("extendTraces", list(y=list(list(ping("8.8.8.8",count = 1)))), list(0))
        }
      })
    }
    

    此处执行30次ping

    要更改ping的频率,请更改 Sys.sleep(1) 到您的链接。