You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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:

  1. 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.
  2. 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.5 in the example) and update the y-axis limit with ax.set_ylim().
  3. Draw the marker:

    • Use ax.scatter() or ax.plot() to place the marker. For triangles, use marker='^' (upward) or marker='v' (downward).
    • Match the marker color to your vertical line for consistency.
    • Set a higher zorder than the vertical line to ensure the marker appears on top.
    • Adjust s (in scatter()) or markersize (in plot()) to make the marker clearly visible.

内容的提问来源于stack exchange,提问作者user1703276

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:53:12