pythonmatplotlibplot-annotations

How to correct coordinate shifting in ax.annotate


I tried to annotate a line plot with ax.annotate as follows.

import numpy as np
import matplotlib.pyplot as plt

x_start = 0
x_end = 200
y_start = 20
y_end = 20

fig, ax = plt.subplots(figsize=(5,5),dpi=600)
ax.plot(np.asarray([i for i in range(0,1000)]))
ax.annotate('', xy=(x_start, y_start), xytext=(x_end, y_end), xycoords='data', textcoords='data',
            arrowprops={'arrowstyle': '|-|'})
plt.show()

which gave a plot (zoomed in)

Although I have specified x_start to be 0 and x_end to be 200, the actual start is greater than 0 and actual end is smaller than 200 on the x-axis.

How do I correctly line up this annotation with the set coordinates?


Solution

  • By default, the arrow is shrunk by 2 points on both ends (see the doc). You can set shrinkA and shrinkB to 0 to align with your x-axis:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x_start = 0
    x_end = 200
    y_start = 20
    y_end = 20
    
    fig, ax = plt.subplots(figsize=(5,5),dpi=600)
    ax.plot(np.asarray([i for i in range(0,1000)]))
    ax.annotate('', xy=(x_start, y_start), xytext=(x_end, y_end), xycoords='data', textcoords='data',
                arrowprops={'arrowstyle': '|-|', 'shrinkA': 0, 'shrinkB': 0})
    plt.show()
    

    Output:

    enter image description here