有没有办法优雅地在圆圈内绘制箭头

时间:2019-07-01 23:03:12

标签: python matplotlib

我试图在单位圆中绘制单位矢量。

这是代码

vunit = 1/np.sqrt(2)
vec1 = [vunit,vunit]
thetas = np.arange(-np.pi, np.pi, .05)
coordinates = np.vstack((np.cos(thetas),np.sin(thetas)))

plt.figure(figsize = (6,6))
plt.xlim(-3,3)
plt.ylim(-3,3)
plt.scatter(coordinates[0,:],coordinates[1,:],s=.1)
plt.arrow(0, 0, vec1[0], vec1[1], head_width=0.15, color='r')

enter image description here

一切正常,除了箭头的箭头在圆的外面。

所以,我丑陋地修改了vec1

vec1 = [vunit-.1,vunit-.1]

enter image description here

该图看起来更好,我可以更精细地修改vec1,但此修复似乎很难看。有没有办法让箭头优雅地进入圆圈

2 个答案:

答案 0 :(得分:6)

使用length_includes_head=True

import numpy as np
import matplotlib.pyplot as plt

vunit = 1/np.sqrt(2)
vec1 = [vunit,vunit]
thetas = np.arange(-np.pi, np.pi, .05)
coordinates = np.vstack((np.cos(thetas),np.sin(thetas)))

plt.figure(figsize = (6,6))
plt.xlim(-3,3)
plt.ylim(-3,3)
plt.scatter(coordinates[0,:],coordinates[1,:],s=.1)
plt.arrow(0, 0, vec1[0], vec1[1], head_width=0.15, color='r', length_includes_head=True)
plt.show()

enter image description here

答案 1 :(得分:1)

一个人可能使用FancyArrowPatch而不是FancyArrowplt.arrow产生的对象)。
这里的差异很小,但是对于其他情况和一致性,FancyArrowPatch提供了许多不错的功能,而FancyArrow则没有。缩放绘图时,可以观察到一个主要区别。 FancyArrow的头部是在数据坐标中定义的,因此,在以非等长图显示时,它将显得偏斜。

enter image description here

这是FancyArrowPatch的完整代码,其中,我们通过shrinkB参数将头顶指向末端坐标。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch

vunit = 1/np.sqrt(2)
vec1 = [vunit,vunit]
thetas = np.arange(-np.pi, np.pi, .05)
coordinates = np.vstack((np.cos(thetas),np.sin(thetas)))

plt.figure(figsize = (6,6))
plt.xlim(-3,3)
plt.ylim(-3,3)
plt.scatter(coordinates[0,:],coordinates[1,:],s=.1)

arrow = FancyArrowPatch(posA=(0,0), posB=vec1, 
                        arrowstyle='-|>', mutation_scale=20, 
                        shrinkA=0, shrinkB=0, color='r')
plt.gca().add_patch(arrow)

plt.show()

enter image description here

相关问题