Python实时绘图仅显示10个数据点的代码合并求助
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:
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.Track Historical Data: We use a global
historydictionary 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.Optimized CSV Reading: Instead of reloading the entire CSV every second, we track
last_read_rowand only load new rows that haven't been processed yet. This is much more efficient, especially as your CSV grows over time.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
historyfor scrolling back later.Blitting: Using
blit=TrueinFuncAnimationmakes 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
Timecolumn in the CSV is in a format matplotlib can handle (e.g., ISO timestamps like2024-05-20 14:30:00or numeric values like seconds since start). If it's a string, you may need to convert it todatetimeobjects first withpd.to_datetime(new_data['Time']). - Adjusting Display: You can change
DISPLAY_POINTSto 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

