如何在Python中制作测速仪样式图表?Matplotlib能否实现该效果?
Great question! Matplotlib doesn’t come with a built-in speedometer (gauge-style) chart out of the box—so it makes total sense you didn’t spot one in the official gallery. But the good news is you can build a fully functional, custom speedometer using Matplotlib’s core plotting tools, no extra libraries required.
You’ll combine polar axes, colored arcs, tick labels, and a pointer to replicate the classic speedometer look. Here’s a step-by-step breakdown with code:
Core Components to Replicate
- Polar Axes: Perfect for the circular layout—we’ll map speed values to angles (usually a half-circle for speedometers).
- Colored Arcs: To create the segmented "safe/warning/danger" color bands.
- Tick Marks & Labels: To mark speed values around the gauge.
- Needle/Pointer: A line or shape to indicate the current speed.
Complete Example Code
import matplotlib.pyplot as plt import numpy as np # Set up polar axis (speedometer is a half-circle, so we'll adjust angles) fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}, figsize=(6, 6)) ax.set_theta_zero_location('N') # Start angle at the top (12 o'clock) ax.set_theta_direction(-1) # Rotate angles clockwise (matches real speedometers) # Define speed ranges and their corresponding colors speed_segments = [ (0, 40, '#27ae60'), # Green: 0-40 mph (40, 70, '#f39c12'), # Yellow: 40-70 mph (70, 100, '#e74c3c') # Red: 70-100 mph ] # Helper function to convert speed values to polar angles def speed_to_angle(speed): # Map 0-100 speed to 0-180 degrees (half-circle), then convert to radians return np.deg2rad(180 * (speed / 100)) # Draw colored speed bands for start_speed, end_speed, color in speed_segments: start_angle = speed_to_angle(start_speed) end_angle = speed_to_angle(end_speed) ax.plot([start_angle, end_angle], [1, 1], color=color, linewidth=25) # Add speed ticks and labels speed_ticks = [0, 20, 40, 60, 80, 100] tick_angles = [speed_to_angle(s) for s in speed_ticks] ax.set_xticks(tick_angles) ax.set_xticklabels([str(s) for s in speed_ticks], fontsize=12) # Hide radial ticks (we don't need them for a speedometer) ax.set_yticks([]) # Draw the speed needle (set to 65 mph as an example) current_speed = 65 needle_angle = speed_to_angle(current_speed) ax.plot([needle_angle, needle_angle], [0, 0.9], color='#2c3e50', linewidth=4) # Add a central hub for the needle ax.scatter([needle_angle], [0], color='#2c3e50', s=120, zorder=10) # Add a title plt.title("Vehicle Speedometer", y=1.1, fontsize=14) plt.show()
Quick Customizations
- Adjust
figsizeto make the gauge larger/smaller. - Modify
speed_segmentsto match your desired speed ranges and colors. - Replace the needle line with a polygon for a more realistic, tapered look.
- Add text at the center to display the current speed numerically (use
ax.text()). - Change the
linewidthof the colored arcs to make the gauge thicker/thinner.
Why This Works
Matplotlib’s polar axes give you full control over angles and radii, so you can easily map linear speed values to the circular layout of a speedometer. The colored bands are just thick lines drawn between specific angles, and the needle is a simple line anchored at the center.
内容的提问来源于stack exchange,提问作者ignoring_gravity

