在matplotlib中标注维度
我想在matplotlib的图形中标注一些长度,比如点A和点B之间的距离。
为此,我觉得可以用annotate这个功能,来确定箭头的起始和结束位置。或者,也可以用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()
我该如何创建一个双头箭头?更好的是,有没有其他更简单的方法来标记matplotlib图形中的尺寸呢?
2 个回答
2
下面的内容可以让你的图表看起来更有层次感:我们在图上添加了两次注释,使用了不同的箭头样式('<->' 和 '|-|'),然后在这条线的中间放置了一段文字,并用一个边框框住了这条线下面的标签。
axs[0].annotate("", xy=(0, ht), xytext=(w, ht), textcoords=axs[0].transData, arrowprops=dict(arrowstyle='<->'))
axs[0].annotate("", xy=(0, ht), xytext=(w, ht), textcoords=axs[0].transData, arrowprops=dict(arrowstyle='|-|'))
bbox=dict(fc="white", ec="none")
axs[0].text(w/2, ht, "L=200 m", ha="center", va="center", bbox=bbox)
9
你可以通过使用 arrowstyle
属性来改变箭头的样式,比如说:
ax.annotate(..., arrowprops=dict(arrowstyle='<->'))
这样就可以得到一个双头箭头。
如果你想看一个完整的例子,可以在 这里 找到,页面大约三分之一的地方有不同样式的介绍。
至于在图表上标记尺寸的“更好”方法,我一时想不起来有什么特别的。
补充一下:如果你觉得有用,这里有一个完整的例子可以参考:
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()