我想通过指向与函数相切的方向来绘制一个箭头,指示某个点上函数的渐变.我希望此箭头的长度与轴大小成比例,以便在任何缩放级别都可见.
假设我们想绘制x^2at 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()
Run Code Online (Sandbox Code Playgroud)
这是两个缩放级别的样子.要清楚,我想要红线的长度和黑线的方向:

就你而言,这听起来像是你想要的quiver。缩放选项一开始有点令人困惑,并且默认行为与您想要的不同。然而,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()
Run Code Online (Sandbox Code Playgroud)

这里的关键部分是
units='inches', angles='xy', scale=1
Run Code Online (Sandbox Code Playgroud)
angles='xy'指定我们希望箭头的旋转/角度采用数据单位(即在本例中匹配绘制曲线的梯度)。
scale=1告诉它不要自动缩放箭头的长度,而是按照我们指定的单位指定的大小绘制它。
units='inches'告诉quiver将我们解释dx, dy为以英寸为单位。
我不确定scale_units在这种情况下是否确实需要(它应该默认与 相同units),但它允许箭头具有与宽度单位不同的长度单位。
当我调整绘图大小时,角度仍以数据单位为单位,但长度仍以英寸为单位(即屏幕上的恒定长度):
