7

I need to "highlight" a few positions on the x-axis of my charts/graphs where significant events occurred. Since the chart/graph is really all over the place I don't want to add vlines inside the chart/graph area itself but rather add arrows, or lines, on top of the chart/graph area together with a number I can refer to later on when mentioning the event in writing ((A) for example).

I've managed to plot vlines, but the label isn't visible at all. Most of all I would like arrows instead of lines since that would be more clear to the reader...

How I'm plotting right now

plt.vlines(
    x = position[0], 
    ymin = axis_ymax, 
    ymax = axis_ymax + int(axis_ymax * 0.05), 
    linestyles = 'solid', 
    label = '(A)'
).set_clip_on(False)

1 Answer 1

9

You can use ax.annotate to annotate a point in your graph with an arrow.

Using ax.annotate you can choose the annotation, the coordinates of the arrow head (xy), the coordinates of the text (xytext), and any properties you want the arrow to have (arrowprops).

import numpy as np

import matplotlib.pyplot as plt

# Generate some data
x = np.linspace(0, 10, 1000)
y = np.sin(np.exp(0.3*x))

fig, ax = plt.subplots()

ax.plot(x, y)

ax.set_ylim(-2,2)

ax.annotate('First maxima', 
            xy=(np.pi/2., 2), 
            xytext=(np.pi/2., 2.3), 
            arrowprops = dict(facecolor='black', shrink=0.05))

plt.show()

Plot

Sign up to request clarification or add additional context in comments.

2 Comments

Can the arrow be located entirely outside of the graph area? i.e pointing to the x-axis from below, or pointing towards the x-axis from above the "ceiling", so to speak?
Yes if you were to use ax.annotate('First maxima', xy=(np.pi/2., 2), xytext=(np.pi/2., 2.3), arrowprops = dict(facecolor='black', shrink=0.05)) then it would place the arrow at the top of your plot with the text above it. Be careful that you don't place the text too far above the plot though or it will go off screen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.