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

Python实时绘图仅显示10个数据点的代码合并求助

Merging Real-Time CSV Temperature Plotting with Rolling 10-Point Display

Hey there! I get it—combining those two pieces of functionality can feel tricky at first, but let's break it down step by step. The key issues with your current approach are that the first script clears the entire plot every update (making scrolling impossible) and the second uses static simulated data instead of reading from your CSV. Here's a complete, merged solution that meets all your requirements:

Complete Working Code

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# Global variables to track historical data and last read row
history = {'Time': [], 'R1Temp': [], 'R2Temp': [], 'R3Temp': []}
last_read_row = 0
DISPLAY_POINTS = 10  # Number of points to show at once

# Initialize plot
fig, ax = plt.subplots(figsize=(10, 6))
line1, = ax.plot([], [], marker='o', label='Room 1 Temp')
line2, = ax.plot([], [], marker='o', label='Room 2 Temp')
line3, = ax.plot([], [], marker='o', label='Room 3 Temp')

ax.set_xlabel("Time")
ax.set_ylabel("Temperature °C")
ax.set_title("Live Temperature of Rooms (Rolling 10-Point View)")
ax.legend(loc='upper left')
plt.tight_layout()

def animate(i):
    global last_read_row, history
    
    # Read new data from CSV (only rows we haven't processed yet)
    try:
        df = pd.read_csv('x.csv')
        new_data = df.iloc[last_read_row:]
        if not new_data.empty:
            # Update history with new data
            history['Time'].extend(new_data['Time'].tolist())
            history['R1Temp'].extend(new_data['R1Temp'].tolist())
            history['R2Temp'].extend(new_data['R2Temp'].tolist())
            history['R3Temp'].extend(new_data['R3Temp'].tolist())
            last_read_row = len(df)  # Update last read row
    except FileNotFoundError:
        print("CSV file not found. Waiting for data...")
        return line1, line2, line3
    
    # Update line data with all historical points
    line1.set_data(history['Time'], history['R1Temp'])
    line2.set_data(history['Time'], history['R2Temp'])
    line3.set_data(history['Time'], history['R3Temp'])
    
    # Adjust x-axis to show only the last DISPLAY_POINTS if we have enough data
    if len(history['Time']) >= DISPLAY_POINTS:
        # Get the time range of the last 10 points
        start_x = history['Time'][-DISPLAY_POINTS]
        end_x = history['Time'][-1]
        ax.set_xlim(start_x, end_x)
        # Optional: Set x-ticks to match the displayed points
        ax.set_xticks(history['Time'][-DISPLAY_POINTS::2])  # Show every other tick for readability
    else:
        # Auto-scale x-axis if we have fewer than 10 points
        ax.relim()
        ax.autoscale_view()
    
    # Adjust y-axis to fit current data (optional but helpful)
    all_temps = history['R1Temp'] + history['R2Temp'] + history['R3Temp']
    if all_temps:
        ax.set_ylim(min(all_temps) - 1, max(all_temps) + 1)
    
    return line1, line2, line3

# Start the animation
ani = FuncAnimation(fig, animate, interval=1000, blit=True)
plt.show()

Key Explanations

Let's go over the critical parts that make this work:

  1. Avoid plt.cla(): Instead of clearing the entire plot every update, we just update the data of the existing lines. This preserves the plot's state, allowing you to scroll back through historical data.

  2. Track Historical Data: We use a global history dictionary to store all temperature and time data as it's read from the CSV. This ensures we never lose old points, so scrolling works seamlessly.

  3. Optimized CSV Reading: Instead of reloading the entire CSV every second, we track last_read_row and only load new rows that haven't been processed yet. This is much more efficient, especially as your CSV grows over time.

  4. Rolling X-Axis: When we have 10 or more points, we set the x-axis limits to the time range of the last 10 points. New points will push the old ones out of the visible area, but they're still stored in history for scrolling back later.

  5. Blitting: Using blit=True in FuncAnimation makes the animation smoother by only redrawing the parts of the plot that change, instead of the entire figure.

Important Notes

  • Time Column Format: Make sure your Time column in the CSV is in a format matplotlib can handle (e.g., ISO timestamps like 2024-05-20 14:30:00 or numeric values like seconds since start). If it's a string, you may need to convert it to datetime objects first with pd.to_datetime(new_data['Time']).
  • Adjusting Display: You can change DISPLAY_POINTS to show more or fewer points at once. The x-tick logic can be tweaked if you want more/less frequent ticks for readability.
  • Error Handling: The code includes a check for missing CSV files, which will print a message instead of crashing if the file isn't ready yet.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:33:56