Plotly Dash时间序列散点图渲染错乱,如何调整Trace修复?
Hey there! Let me start by saying: the mode='markers+lines' parameter isn't the problem here — that setting works perfectly fine for time series plots (it just adds both points and connecting lines, which is exactly what you want for this use case).
The wonky, jumping behavior you're seeing is almost always caused by one of two issues with your underlying data:
1. Your Data Isn't Sorted by Timestamp
When you pull new data from your MySQL database every 5 seconds, there's no guarantee the rows come back in chronological order. Plotly draws points in the exact order they appear in your DataFrame — if later timestamps are mixed in with earlier ones, the line will jump all over the place instead of flowing smoothly.
Fix: Sort your DataFrame by timestamp first
Before creating your trace, add this line to enforce chronological order:
# Sort the entire DataFrame by timestamp to ensure proper sequence df = df.sort_values('timestamp').reset_index(drop=True)
2. Your Timestamp Column Isn't Recognized as a Datetime Type
If your timestamp column is stored as a string (or another non-datetime format) in your DataFrame, Plotly won't interpret it as a sequential time axis. Instead, it'll treat each value as a discrete category, leading to unexpected, jumbled ordering.
Fix: Convert the timestamp column to datetime
Add this line right after loading your JSON data into a DataFrame:
# Convert timestamp string to proper datetime type for Plotly to interpret correctly df['timestamp'] = pd.to_datetime(df['timestamp'])
Modified Trace Code (with Data Fixes)
Putting it all together, your callback code should look something like this:
# Inside your callback function, after loading JSON data into df df['timestamp'] = pd.to_datetime(df['timestamp']) df = df.sort_values('timestamp').reset_index(drop=True) # Now create your trace with properly ordered, time-aware data trace_sensor_1 = Scatter( x=df.loc[df['sensor_id'] == 1]['timestamp'], y=df.loc[df['sensor_id'] == 1]['sensor_reading'], mode='markers+lines', name='Sensor 1' )
Bonus Tip for Streamed Data
Since you're pulling new data every 5 seconds, make sure when you update your hidden Div's data, you're either:
- Appending new rows to your existing DataFrame (and re-sorting each time), or
- Pulling a window of recent data (e.g., last 10 minutes) and sorting that subset
This will keep your plot smooth and consistent as new sensor readings come in.
内容的提问来源于stack exchange,提问作者Adi

