Luis Luis - 4 months ago 20
Python Question

How to annotate a range of the x axis in matplotlib?

I want to make an annotation, something like here, but I need to show a range in x instead of a single point. It's something like the dimension lines in technical drawing.




Here is an example of what I am looking for:

import matplotlib.pyplot as plt
import numpy as np

xx = np.linspace(0,10)
yy = np.sin(xx)

fig, ax = plt.subplots(1,1, figsize=(12,5))
ax.plot(xx,yy)
ax.set_ylim([-2,2])
# -----------------------------------------
# The following block attempts to show what I am looking for
ax.plot([4,6],[1,1],'-k')
ax.plot([4,4],[0.9,1.1],'-k')
ax.plot([6,6],[0.9,1.1],'-k')
ax.annotate('important\npart', xy=(4, 1.5), xytext=(4.5, 1.2) )


enter image description here




How do I annotate a range in a maplotlib graph?




I am using:

python: 3.4.3 + numpy: 1.11.0 + matplotlib: 1.5.1

Answer

You could use two calls to ax.annotate - one to add the text and one to draw an arrow with flat ends spanning the range you want to annotate:

import matplotlib.pyplot as plt
import numpy as np

xx = np.linspace(0,10)
yy = np.sin(xx)

fig, ax = plt.subplots(1,1, figsize=(12,5))
ax.plot(xx,yy)
ax.set_ylim([-2,2])

ax.annotate('', xy=(4, 1), xytext=(6, 1), xycoords='data', textcoords='data',
            arrowprops={'arrowstyle': '|-|'})
ax.annotate('important\npart', xy=(5, 1.5), ha='center', va='center')

enter image description here

Comments