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...):
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...
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
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)
).
Try using annotate
:
annotate ('', (0.4, 0.2), (0.4, 0.8), arrowprops={'arrowstyle':'<->'})
I'm not sure about automatic text placement though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With