Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotating dimensions in matplotlib

I want to annotate certain lengths in a matplotlib figure. For example, the distance between points A and B.

For this, I think I can either use annotate and figure out how to supply the start and end positions of the arrow. Or, use arrow and label the point.

I tried to use the latter, but I can't figure out how to get a 2-headed arrow:

from pylab import *

for i in [0, 1]:
    for j in [0, 1]:
        plot(i, j, 'rx')

axis([-1, 2, -1, 2]) 
arrow(0.1, 0, 0, 1, length_includes_head=True, head_width=.03) # Draws a 1-headed arrow
show()

How do I create a 2-headed arrow? Better still, is there another (simpler) way of marking dimensions in matplotlib figures?

like image 665
Dhara Avatar asked Jun 09 '26 16:06

Dhara


1 Answers

You can change the style of an arrow by using the arrowstyle property, for example

ax.annotate(..., arrowprops=dict(arrowstyle='<->'))

gives a double headed arrow.

A complete example can be found here about a third the way down the page with the possible different styles.

As for a 'better' way of marking dimensions on plots I cannot think of any off the top of my head.

Edit: here's a complete example you can use if it's helpful

import matplotlib.pyplot as plt
import numpy as np

def annotate_dim(ax,xyfrom,xyto,text=None):

    if text is None:
        text = str(np.sqrt( (xyfrom[0]-xyto[0])**2 + (xyfrom[1]-xyto[1])**2 ))

    ax.annotate("",xyfrom,xyto,arrowprops=dict(arrowstyle='<->'))
    ax.text((xyto[0]+xyfrom[0])/2,(xyto[1]+xyfrom[1])/2,text,fontsize=16)

x = np.linspace(0,2*np.pi,100)
plt.plot(x,np.sin(x))
annotate_dim(plt.gca(),[0,0],[np.pi,0],'$\pi$')

plt.show()
like image 76
Dan Avatar answered Jun 11 '26 20:06

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!