要使 plt.hist2d 返回实际变量,您可以使用 np.histogram2d 函数来计算直方图,并使用 plt.imshow 来显示直方图结果。下面是一个示例代码:
import numpy as np
import matplotlib.pyplot as plt
# 生成随机数据
x = np.random.randn(1000)
y = np.random.randn(1000)
# 计算直方图
hist, xedges, yedges = np.histogram2d(x, y, bins=10)
# 显示直方图
plt.imshow(hist, origin='lower', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], cmap='Blues')
plt.colorbar()
plt.show()
在这个示例中,我们使用 np.histogram2d 函数计算了 x 和 y 数据的直方图,并将结果存储在 hist 变量中。然后,我们使用 plt.imshow 函数来显示直方图结果,其中 origin='lower' 用于指定原点在左下角,extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]] 用于调整显示范围。最后,我们使用 plt.colorbar 添加一个颜色条来表示值的范围,并使用 plt.show 显示图形。
希望这个示例能帮助到您!