Plotting distance arrows in technical drawing


I want to indicate a distance in one of my plots. What I have in mind is the way they do it in technical drawings, showing a double headed arrow with the distance as text beside it.


from matplotlib.pyplot import *

hlines(7,0,2, linestyles='dashed')
hlines(11,0,2, linestyles='dashed')
hlines(10,0,2, linestyles='dashed')
hlines(8,0,2, linestyles='dashed')
plot((1,1),(8,10), 'k',) # arrow line
plot((1,1),(8,8), 'k', marker='v',) # lower arrowhead
plot((1,1),(10,10), 'k', marker='^',) # upper arrowhead

This results in something like this (two of the hlines are not really needed, they just increase the drawing area...): Distance marker manual style

Is there a quicker way to do this, preferably with arrowheads which end on the exact spot, not below/above where they should be? Extra points for placing the text automatically as well.

Edit: I had been playing with annotate but since the string would have to be sacrificed this solution had lost some appeal to me. Thanks for pointing out the arrowstyle though, it wasn't working when I attempted something similar. I guess there is no way around writing a little function to do it with one call...

1/31/2013 10:25:04 AM

Accepted Answer

import matplotlib.pyplot as plt

plt.hlines(7, 0, 2, linestyles='dashed')
plt.hlines(11, 0, 2, linestyles='dashed')
plt.hlines(10, 0, 2, linestyles='dashed')
plt.hlines(8, 0, 2, linestyles='dashed')
    '', xy=(1, 10), xycoords='data',
    xytext=(1, 8), textcoords='data',
    arrowprops={'arrowstyle': '<->'})
    'D = 1', xy=(1, 9), xycoords='data',
    xytext=(5, 0), textcoords='offset points')

# alternatively,
# plt.text(1.01, 9, 'D = 1')


enter image description here

For more information on the many options available with plt.annotate, see this page.

As shown above, the text can be placed with either plt.annotate or plt.text. With plt.annotate you can specify the offset (e.g. (5, 0)) in points, whereas with plt.text you can specify the text location in data coordinates (e.g. (1.01, 9)).

10/18/2014 4:16:45 PM

Try using annotate:

annotate ('', (0.4, 0.2), (0.4, 0.8), arrowprops={'arrowstyle':'<->'})

Image produced by annotate command

I'm not sure about automatic text placement though.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow