如何创建离散二维直方图
How to create a discrete 2d-Histogram plot
我正在尝试绘制二维直方图,显示两次测量之间收到的错误代码之间的相关性。错误代码值的范围从 -3 到 5。我希望直方图为每个错误代码显示一个条形图。在由一次测量收到的两个错误代码标记的字段中,条形应该增加(改变颜色)。我在这里画了一个小草图。
到目前为止我只有下面的代码,不幸的是它没有给我想要的情节。有人知道如何按照我上面的描述获得情节吗?
data1=np.random.randint(-3,5,100)
data2=np.random.randint(-3,5,100)
fig, ax = plt.subplots()
ax.hist2d(data1, data2, bins=10)
plt.Axes.set_xlim(ax,left=-3, right=6)
plt.Axes.set_ylim(ax, bottom=-3, top=6)
plt.grid(True)
plt.show()
您需要正确的 bins
数量和轴限制以获得所需的可视化效果。此外,当您使用 data1=np.random.randint(-3,5,100)
时,您得到的最高整数是 4 而不是 5。下面是您的代码的修改版本。
data1=np.random.randint(-3,6,100)
data2=np.random.randint(-3,6,100)
n_bins = len(set(data1.flatten())) - 1
l = -3
r = 5
fig, ax = plt.subplots()
im = ax.hist2d(data1, data2, bins=n_bins+1)
ax.set_xlim(left=l, right=r)
ax.set_ylim(bottom=l, top=r)
shift = (im[1][1]-im[1][0])/2
plt.xticks(im[1], range(l, r+1, 1))
plt.yticks(im[1], range(l, r+1, 1))
plt.grid(True)
plt.colorbar(im[3])
plt.show()
我正在尝试绘制二维直方图,显示两次测量之间收到的错误代码之间的相关性。错误代码值的范围从 -3 到 5。我希望直方图为每个错误代码显示一个条形图。在由一次测量收到的两个错误代码标记的字段中,条形应该增加(改变颜色)。我在这里画了一个小草图。
到目前为止我只有下面的代码,不幸的是它没有给我想要的情节。有人知道如何按照我上面的描述获得情节吗?
data1=np.random.randint(-3,5,100)
data2=np.random.randint(-3,5,100)
fig, ax = plt.subplots()
ax.hist2d(data1, data2, bins=10)
plt.Axes.set_xlim(ax,left=-3, right=6)
plt.Axes.set_ylim(ax, bottom=-3, top=6)
plt.grid(True)
plt.show()
您需要正确的 bins
数量和轴限制以获得所需的可视化效果。此外,当您使用 data1=np.random.randint(-3,5,100)
时,您得到的最高整数是 4 而不是 5。下面是您的代码的修改版本。
data1=np.random.randint(-3,6,100)
data2=np.random.randint(-3,6,100)
n_bins = len(set(data1.flatten())) - 1
l = -3
r = 5
fig, ax = plt.subplots()
im = ax.hist2d(data1, data2, bins=n_bins+1)
ax.set_xlim(left=l, right=r)
ax.set_ylim(bottom=l, top=r)
shift = (im[1][1]-im[1][0])/2
plt.xticks(im[1], range(l, r+1, 1))
plt.yticks(im[1], range(l, r+1, 1))
plt.grid(True)
plt.colorbar(im[3])
plt.show()