如何在 matplotlib.pyplot 中使用带有 hist2d 的颜色条?

要在matplotlib.pyplot中将colorbar 与hist2d一起使用,我们可以采取以下步骤。

步骤

  • 设置图形大小并调整子图之间和周围的填充。

  • 为样本数据的数量初始化一个变量“N”

  • 使用 numpy创建xy数据点。

  • subplots()使用方法创建一个图形和一组子图。

  • 使用 hist2 制作二维直方图D()。

  • 为hist2d标量可映射实例创建一个颜色条。

  • 要显示图形,请使用Show()方法。

示例

frommatplotlib.colorsimport LogNorm
importmatplotlib.pyplotas plt
import numpy as np

# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Number of sample data
N = 1000

# Create x and y data points
x = np.random.rand(N)
y = np.random.rand(N)

fig, ax = plt.subplots()

# 2D histogram plot with x and y
hh = ax.hist2d(x, y, bins=40, norm=LogNorm())

fig.colorbar(hh[3], ax=ax)

# Display the plot
plt.show()
输出结果

它将产生以下输出 -