箭头方向由数据设置,但长度由图形大小

时间:2015-07-17 00:16:34

标签: python matplotlib

我想通过指向与函数相切的方向来绘制一个箭头,指示某个点上函数的渐变。我希望此箭头的长度与轴大小成比例,以便在任何缩放级别都可见。

假设我们想在x^2处绘制x=1的导数(导数为2)。以下是我尝试过的两件事:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

x = np.linspace(0, 2, 1000)
y = x**2
ax.plot(x, y)

x, y = (1.0, 1.0)
grad = 2.0

# Fixed size, wrong direction
len_pts = 40
end_xy = (len_pts, len_pts*grad)

ax.annotate("", xy=(x, y), xycoords='data',
        xytext=end_xy, textcoords='offset points',
        arrowprops=dict(arrowstyle='<-', connectionstyle="arc3"))

# Fixed direction, wrong size
len_units = 0.2
end_xy = (x+len_units, y+len_units*grad)

ax.annotate("", xy=(x, y), xycoords='data',
        xytext=end_xy, textcoords='data',
        arrowprops=dict(arrowstyle='<-', connectionstyle="arc3"))

ax.axis((0,2,0,2))
plt.show()

这是两个缩放级别的样子。要清楚,我想要红线的长度和黑线的方向

enter image description here enter image description here

1 个答案:

答案 0 :(得分:4)

在您的情况下,听起来像是您想quiver。缩放选项最初有点令人困惑,默认行为与您想要的不同。但是,箭头的整个点是让您在调整绘图大小时控制大小,角度和缩放的相互作用。

例如:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

x = np.linspace(0, 2, 1000)
y = x**2
ax.plot(x, y)

x0, y0 = 1.0, 1.0
dx, dy = 1, 2

length = 1.25 # in inches
dx, dy = length * np.array([dx, dy]) / np.hypot(dx, dy)

ax.quiver(x0, y0, dx, dy, units='inches', angles='xy', scale=1,
          scale_units='inches', color='red')

ax.axis((0, 2, 0, 2))
plt.show()

enter image description here

这里的关键部分是

units='inches', angles='xy', scale=1

angles='xy'指定我们希望箭头的旋转/角度为数据单位(即匹配绘制曲线的渐变,在本例中)。

scale=1告诉它不要自动缩放箭头的长度,而是将它绘制为我们用我们指定的单位给它的大小。

units='inches'告诉quiverdx, dy解释为以英寸为单位。

我不确定在这种情况下实际需要scale_units(它应默认为与units相同),但它允许箭头具有与宽度单位不同的长度单位

当我调整绘图大小时,角度保持在数据单位,但长度保持在英寸(即屏幕上的恒定长度):

enter image description here