我正在尝试绘制箭头以可视化热图上的梯度。这是我到目前为止的代码:
import matplotlib.pyplot as plt
import numpy as np
function_to_plot = lambda x, y: x + y ** 2
horizontal_min, horizontal_max, horizontal_stepsize = 0, 3, 0.3
vertical_min, vertical_max, vertical_stepsize = 0, 3, 0.6
xv, yv = np.meshgrid(np.arange(horizontal_min, horizontal_max, horizontal_stepsize),
np.arange(vertical_min, vertical_max, vertical_stepsize))
result_matrix = function_to_plot(xv, yv)
xd, yd = np.gradient(result_matrix)
def func_to_vectorize(x, y, dx, dy, scaling=1):
plt.arrow(x + horizontal_stepsize/2, y + vertical_stepsize/2, dx*scaling, dy*scaling, fc="k", ec="k", head_width=0.1, head_length=0.1)
vectorized_arrow_drawing = np.vectorize(func_to_vectorize)
plt.imshow(result_matrix, extent=[horizontal_min, horizontal_max, vertical_min, vertical_max])
vectorized_arrow_drawing(xv, yv, xd, yd, …Run Code Online (Sandbox Code Playgroud)