在 matplotlib 的字符串轴上设置注释位置 python

Set location of annotation on string-axis on matplotlib python

我需要在绘图的最后三个数据点上添加注释。
下面的列表 x2 用作字符串列表的 x 轴。
列表 x2 是从列表 x1 转换而来的年月格式。

我的问题是如何调整我的注释在字符串轴中的 x 位置,例如 x2
我需要将注释向左移动一点,以便它们可以位于数据点的中心。

import matplotlib.pyplot as plt

x1 = ["2020-01-01","2020-02-01","2020-03-01","2020-04-01","2020-05-01",
      "2020-06-01","2020-07-01","2020-08-01","2020-09-01","2020-10-01"]

x2 = ["109-01","109-02","109-03","109-04","109-05","109-06","109-07","109-08","109-09","109-10"]

y = [2288, 2638, 3088, 2684, 3033, 2940, 3634, 3219, 3505, 3223]

fig, ax = plt.subplots(figsize=(18,9))

ax.plot(x2, y)

label_x = x2[-3:]
label_y = y[-3:]
for i, txt in enumerate(label_y):
    ax.annotate(txt, (label_x[i], label_y[i]+100))

this tutorial page 判断,annotate 函数的文本应采用 horizontalalignment 属性(来自链接页面的代码):

ax.annotate('local max', xy=(3, 1),  xycoords='data',
            xytext=(0.8, 0.95), textcoords='axes fraction',
            arrowprops=dict(facecolor='black', shrink=0.05),
            horizontalalignment='right', verticalalignment='top',
            )

另见 this page about the text properties

意思是你应该能够做类似的事情:

for i, txt in enumerate(label_y):
    ax.annotate(txt, (label_x[i], label_y[i]+100), horizontalalignment='center')