Reputation: 121
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. 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()
Upvotes: 1
Views: 801
Reputation: 39042
You need the correct number of bins
and the axis limits to get the desired visualization. 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,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()
Upvotes: 2