【问题标题】:Update the data for ggplot2 line graph using the loop使用循环更新 ggplot2 折线图的数据
【发布时间】:2018-03-31 08:17:37
【问题描述】:

您好,我是编程新手,我是“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

}

我想让它看起来像 speedtest.net 上的酷图。但是这个每次循环都会重绘整个情节,这需要太多时间。有没有其他办法?

【问题讨论】:

  • 嗯,我认为 ggplot2 方法可能不是最好的,甚至不是“正确”的工具/方法。您应该查看shiny。 ggplot2 是为漂亮的静态图形而设计的,而 shiny 是为动态显示数据/图形而创建的。
  • 会试试的:)谢谢
  • @Amar 你仍然需要一个包来在 Shiny 中绘图。
  • 如果不是太麻烦的话..你能分享一个闪亮的示例代码来实现这个结果吗?所以在我阅读有关闪亮的教程之前,我会知道这是否是我正在寻找的东西。如果制作起来不是很容易,请忽略

标签: r loops ggplot2 ping


【解决方案1】:

下面是一个示例,如何使用闪亮和情节设置所需的行为:

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

一个带有开始按钮和绘图区的简单用户界面:

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)

一段时间后它看起来像这样:

编辑:回答评论中的问题: 有多种方法可以控制 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) 更改为您的链接。

【讨论】:

  • 谢谢 :) 我会试试的
  • 嘿,我收到了这个错误;友善的建议。监听127.0.0.1:6004 错误:[on_request_read] 连接被对等方重置 origRenderFunc() 中的警告:忽略显式提供的小部件 ID“231439807955”; Shiny 不使用它们
  • 没关系,它在“在窗口上运行”上运行良好 :) 谢谢!但是我们在代码的什么地方提到了要执行的 ping 次数?
  • 更新了答案。请检查。
  • 谢谢@missuse :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-29
相关资源
最近更新 更多