如何在Matplotlib的axvline垂直线顶部添加三角形符号
Add Triangle Marker at Top of Matplotlib Vertical Line
Let's fix your code first, then break down the general method for adding markers to vertical line tops in Matplotlib.
Modified Full Code
First, we'll adjust your existing code to handle dates properly, locate the vertical line's exact position, and add the triangle marker:
import matplotlib.pyplot as plt import matplotlib.dates as mdates import pandas as pd # Convert date strings to datetime objects (critical for accurate positioning) df = pd.DataFrame({ 'A': {0: '2020-01-01 06:00:00', 1: '2020-01-01 18:00:00', 2: '2020-01-02 06:00:00', 3: '2020-01-02 18:00:00', 4: '2020-01-03 06:00:00', 5: '2020-01-03 18:00:00', 6: '2020-01-04 06:00:00', 7: '2020-01-04 18:00:00'}, 'B': {0:5, 1:5, 2:6, 3:6, 4:7, 5:7, 6:1, 7:1} }) df['A'] = pd.to_datetime(df['A']) fig, ax = plt.subplots(1) ax.bar(df['A'], df['B'], linestyle='-', color='midnightblue', lw=6, width=0.01) plt.xticks(rotation=90) # Define the vertical line's target date vline_date = pd.to_datetime('2020-01-02 18:00:00') # Draw the vertical line ax.axvline(vline_date, color='red', zorder=1, linestyle='--') # Convert date to Matplotlib's numerical format for positioning x_pos = mdates.date2num(vline_date) # Get the top of the current y-axis y_top = ax.get_ylim()[1] # Add upward triangle marker at the line's top ax.scatter(x_pos, y_top, marker='^', color='red', s=100, zorder=2) # s controls marker size # Optional: Adjust y-axis to prevent marker from being cut off ax.set_ylim(bottom=0, top=y_top + 0.5) plt.tight_layout() plt.show()
General Method for Adding Markers to Vertical Line Tops
This approach works for any vertical line in Matplotlib, regardless of whether you're using dates or numerical x-values:
Get the vertical line's x-position:
- For dates: Convert your date string/datetime object to Matplotlib's numerical date format with
mdates.date2num(). - For numerical values: Use the exact value you passed to
axvline()directly.
- For dates: Convert your date string/datetime object to Matplotlib's numerical date format with
Set the marker's y-position:
- Use
ax.get_ylim()[1]to grab the current top of the y-axis. - If you want the marker slightly above the plot content, add a small offset (like
y_top + 0.5in the example) and update the y-axis limit withax.set_ylim().
- Use
Draw the marker:
- Use
ax.scatter()orax.plot()to place the marker. For triangles, usemarker='^'(upward) ormarker='v'(downward). - Match the marker color to your vertical line for consistency.
- Set a higher
zorderthan the vertical line to ensure the marker appears on top. - Adjust
s(inscatter()) ormarkersize(inplot()) to make the marker clearly visible.
- Use
内容的提问来源于stack exchange,提问作者user1703276
相关产品推荐
相关产品推荐

