简体   繁体   English

如何创建离散的2D直方图

[英]How to create a discrete 2d-Histogram plot

I am trying to plot a 2d histogram showing the correlation between the error codes received between two measurements. 我试图绘制一个二维直方图,显示两次测量之间收到的错误代码之间的相关性。 The error code values range from -3 to 5. I would like the histogram to show a bar for every error code. 错误代码值的范围是-3到5。我希望直方图显示每个错误代码的条形图。 The bars should increase (change color) in the field marked by the two error codes received for one measurement. 在一次测量中收到的两个错误代码标记的栏中,条形应该增加(更改颜色)。 I have drawn a short sketch here. 我在这里画了一个简短的草图。 在此处输入图片说明

So far I only have the code below, which unfortunately does not give me the desired plot. 到目前为止,我只有下面的代码,不幸的是它没有给我想要的绘图。 Does anybody know how to get a plot as I described above? 有人知道如何获得如上所述的情节吗?

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()

You need the correct number of bins and the axis limits to get the desired visualization. 您需要正确数量的bins和轴限制,才能获得所需的可视化效果。 Moreover, when you use data1=np.random.randint(-3,5,100) , the highest integer you get it 4 and not 5. Below is a modified version of your code. 此外,当您使用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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM