Set location of annotation on string-axis

Question:

I need to add annotations over last three data points on my plot.
Below list x2 is used as x-axis which a string list.
List x2 is a year-month format converted from list x1.

My question is how to adjust the x location of my annotation in string-axis such as x2?
I need to move annotations a bit more left so they can located at the center of their data point.

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))

plot_output

Asked By: Pete

||

Answers:

Judging from this tutorial page, the annotate function should take a horizontalalignment property for its text (code from the page linked):

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',
            )

See also this page about the text properties.

Meaning you should be able to do something like:

for i, txt in enumerate(label_y):
    ax.annotate(txt, (label_x[i], label_y[i]+100), horizontalalignment='center')
Answered By: fravolt
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.