Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using matplotlib and point to specific value on the x-axis

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)
like image 700
user3235200 Avatar asked Apr 26 '14 13:04

user3235200


Video Answer


1 Answers

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

like image 64
Ffisegydd Avatar answered Sep 28 '22 11:09

Ffisegydd