gpt4 book ai didi

python - 如何创建离散二维直方图

转载 作者:行者123 更新时间:2023-12-01 01:17:31 24 4
gpt4 key购买 nike

我正在尝试绘制二维直方图,显示两次测量之间收到的错误代码之间的相关性。错误代码值的范围从 -3 到 5。我希望直方图为每个错误代码显示一个条形。在由一次测量收到的两个错误代码标记的字段中,条形应增加(改变颜色)。我在这里画了一个简短的草图。 enter image description here

到目前为止,我只有下面的代码,不幸的是,它没有给我想要的情节。有人知道如何获得我上面描述的情节吗?

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

enter image description here

关于python - 如何创建离散二维直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54179907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com