如何用Python在单张图中绘制车辆速度数据并标注城市信息?
Step-by-Step Guide to Create Your Time-Speed Chart with City Annotations
Hey there! Let's walk through this together—since you're new to Python data visualization, I'll keep things clear and actionable. Here's how to get your desired chart with a proper time axis and city labels for speed=0 points:
1. First, Fix the Time Data Type
Chances are your time column is stored as a string right now, which will mess up the X-axis ordering. Let's convert it to a proper datetime format first:
import pandas as pd import matplotlib.pyplot as plt # If you haven't loaded your Excel data yet, add this line: # Dataset = pd.read_excel("your_data_file.xlsx") # Convert time column to datetime (critical for correct time axis behavior) Dataset['time'] = pd.to_datetime(Dataset['time'])
2. Plot the Basic Speed-Time Curve
Now let's draw the core speed curve with a properly formatted time X-axis:
plt.figure(figsize=(12, 6)) # Set a comfortable chart size # Plot speed over time plt.plot(Dataset['time'], Dataset['speed'], label='Speed', color='steelblue', linewidth=2) # Add clear labels and title plt.xlabel('Time', fontsize=12) plt.ylabel('Speed', fontsize=12) plt.title('Speed Over Time (City Labels for Speed=0)', fontsize=14) plt.legend() # Rotate X-axis ticks to avoid overlap (a must for time-based data) plt.xticks(rotation=45) plt.tight_layout() # Adjusts layout so labels don't get cut off
3. Add City Annotations for Speed=0 Points
Next, we'll target all rows where speed is 0 and label the corresponding city at those points:
# Filter rows where speed equals 0 zero_speed_rows = Dataset[Dataset['speed'] == 0] # Loop through each zero-speed entry to add annotations for idx, row in zero_speed_rows.iterrows(): # Place the city label slightly above the speed=0 point to avoid curve overlap plt.annotate( text=row['city'], xy=(row['time'], row['speed']), xytext=(0, 10), # Offset text 10 points upward from the data point textcoords='offset points', fontsize=10, color='crimson', weight='bold' ) # Display the final chart plt.show()
Quick Tips for Your Workflow:
- If your
speedcolumn has non-numeric values, clean it first withDataset['speed'] = pd.to_numeric(Dataset['speed'], errors='coerce')to handle any bad data entries. - Tweak the
xytextvalue (the 10) if you want labels closer or farther from the speed=0 points. - If you prefer a fancier style, swap
plt.plotwithsns.lineplot(data=Dataset, x='time', y='speed')—the annotation code works the same way!
内容的提问来源于stack exchange,提问作者Pierpaolo Regnante
相关产品推荐
相关产品推荐

