You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新手求助:如何通过循环更新ggplot2折线图数据?附R语言ping测试代码

Hey there! Let's get your real-time ping latency plot working smoothly. I see you're new to R and programming, so I'll break this down clearly with a revised code example and explanations of the key fixes.

Fixed Code for Real-Time Ping Plot Updates

Here's a cleaned-up, working version of your code that updates the ggplot2 line plot with each ping:

library(pingr)
library(ggplot2)

# Start with an empty data frame to store our ping results (more efficient than growing vectors)
ping_data <- data.frame(counts = integer(), pings = numeric())

# Set how many total pings we want to run
total_pings <- 300

# Loop through each ping iteration
for (current_ping in 1:total_pings) {
  # Run a single ping to Google's DNS server
  latency <- ping("8.8.8.8", count = 1)
  
  # Add the new result to our data frame
  ping_data <- rbind(ping_data, data.frame(counts = current_ping, pings = latency))
  
  # Build the updated plot
  ping_plot <- ggplot(ping_data, aes(x = counts, y = pings)) +
    geom_line(color = "red") +
    coord_cartesian(xlim = c(0, total_pings), ylim = c(0, 100)) +
    labs(
      title = "Real-Time Ping Latency to 8.8.8.8",
      x = "Ping Number",
      y = "Latency (milliseconds)"
    )
  
  # Print the plot to update it in your console/plot window
  print(ping_plot)
  
  # Add a 1-second delay between pings (adjust this if you want faster/slower updates)
  Sys.sleep(1)
}
Key Improvements & Fixes

Let's go over what changed and why:

  • Preinitialized Data Frame: Instead of constantly expanding counts and pings vectors, we start with an empty data frame and add rows as we go. This is more efficient in R and avoids messy vector concatenation.
  • Cleaner For Loop: Using a for loop from 1 to total_pings is simpler than managing a counter with a while loop — no need to track cc manually!
  • Proper Plot Printing: ggplot2 objects need to be explicitly printed with print() when inside loops. Your original code had an incomplete print(...) line, which would have caused errors.
  • Fixed Syntax: Your coord_cartesian line had extra parentheses around the xlim/ylim values — we removed those to fix the syntax error.
  • Added Delay: Sys.sleep(1) adds a 1-second pause between pings, so you don't flood the network and the plot updates are easier to follow.
  • Better Labels: Added clear titles and axis labels to make the plot more readable.
Bonus Tip for Later

If you want a more polished interactive dashboard down the line, check out the shiny package — it lets you build web apps that update plots automatically without needing a loop. But for your current testing needs, the code above should work perfectly.

内容的提问来源于stack exchange,提问作者Jac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:26:37