Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting distance arrows in technical drawing

Tags:

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.

Example:

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
text(1.1,9,"D=1")

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...

like image 426
BandGap Avatar asked Jan 30 '13 20:01

BandGap


2 Answers

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')
plt.annotate(
    '', xy=(1, 10), xycoords='data',
    xytext=(1, 8), textcoords='data',
    arrowprops={'arrowstyle': '<->'})
plt.annotate(
    'D = 1', xy=(1, 9), xycoords='data',
    xytext=(5, 0), textcoords='offset points')

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

plt.show()

yields

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)).

like image 75
unutbu Avatar answered Oct 11 '22 18:10

unutbu


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.

like image 35
lxop Avatar answered Oct 11 '22 17:10

lxop