如何在matplotlib.pyplot第二个子图添加水平线并保持颜色同步?
Solution: Add Horizontal Line with Matching Colors in Matplotlib Subplots
Hey there! Let's tackle your problem step by step—you want to add a horizontal line at y=100.000 to your second subplot, while keeping both subplots (and the line) using the same color. Here are two straightforward approaches:
Approach 1: Inherit the color from your first plot
This method automatically picks up the color of your first curve, so you don't have to hardcode any color values:
import matplotlib.pyplot as plt # Replace these with your actual data px = [1, 2, 3, 4, 5] py = [10, 20, 15, 25, 30] curve = [50, 75, 90, 100, 120, 110] # First subplot: plot and capture the line's color plt.subplot(2, 1, 1) # The comma extracts the single Line2D object from the returned list line1, = plt.plot(px, py) plot_color = line1.get_color() # Get the color of the first line # Second subplot: use the same color for the curve and horizontal line plt.subplot(2, 1, 2) plt.plot(curve, color=plot_color) # Add the horizontal line at y=100.000, matching the plot color plt.axhline(y=100.000, color=plot_color, linestyle='--', label='100.000') # Optional: Add a legend to highlight the horizontal line plt.legend() # Adjust spacing to prevent overlapping labels plt.tight_layout() plt.show()
Approach 2: Manually specify a unified color
If you prefer to control the exact color, just define a color value upfront and use it for all elements:
import matplotlib.pyplot as plt # Define your desired color (use any valid matplotlib color: hex, name, RGB tuple) plot_color = '#1f77b4' # Matplotlib's default blue # Your data (replace with real values) px = [1, 2, 3, 4, 5] py = [10, 20, 15, 25, 30] curve = [50, 75, 90, 100, 120, 110] plt.subplot(2, 1, 1) plt.plot(px, py, color=plot_color) plt.subplot(2, 1, 2) plt.plot(curve, color=plot_color) # Add horizontal line with the same color plt.axhline(y=100.000, color=plot_color, linestyle='--') plt.tight_layout() plt.show()
Key Notes:
- The
plt.axhline()function is perfect for horizontal lines—it spans the entire width of the subplot by default. - Use
linestyle(like'--'for dashed,':'for dotted) to distinguish the horizontal line from your main curve if needed. plt.tight_layout()ensures your subplots and labels don't overlap, making the figure cleaner.
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

