首页 > 解决方案 > matplotlib 颜色条显示每个 bin 的密度

问题描述

我有以下数据,我正在为其绘制二维直方图

data1 = [68, 64, 59, 65, 69, 64, 67, 67, 62, 64, 66, 64, 67, 
60, 64, 67, 67, 66, 62, 61, 63, 66, 67, 67, 68, 71, 60, 65, 66, 
64, 64, 65, 68, 69, 68, 61, 63, 67, 63, 61, 68, 66, 67, 63, 72, 
68, 63, 68]

data2 = [21.5, 18.0, 20.0, 21.0, 20.5, 18.5, 21.0, 19.5, 20.0, 
18.5, 20.5, 18.5, 18.0, 19.5, 21.0, 20.0, 20.0, 19.0, 17.0, 
17.5, 19.0, 18.5, 20.5, 19.5, 20.0, 20.0, 18.5, 20.0, 21.0, 
19.5, 20.0, 20.0]

data3 = data1[:32]

代码:

fig, ax = plt.subplots()
ax.set_aspect("equal")
hist, xbins, ybins, im = ax.hist2d(data3,data2, bins=(8,8))

for i in range(len(ybins)-1):
    for j in range(len(xbins)-1):
        ax.text(xbins[j]+0.3,ybins[i]+0.3, hist[i,j],color="w",ha="center", va="center", fontweight="bold")

plt.colorbar(im, ax=ax, norm=mcolors.NoNorm)

我得到了这个情节。 在此处输入图像描述

我想要实现的是每个 bin 的颜色根据其中的值表示。目前,我看到 bin 的颜色相同,值为 3、1 和 0。

标签: pythonmatplotlibhistogram

解决方案


您放置索引是错误的。

你应该使用: hist[j,i]

这是错误: hist[i,j]

因此这段代码是正确的:

fig, ax = plt.subplots(figsize=(10,10))
ax.set_aspect("equal")
hist, xbins, ybins, im = ax.hist2d(data3,data2, bins=(8,8))

for i in range(len(ybins)-1):
    for j in range(len(xbins)-1):
        ax.text(xbins[j]+0.3,ybins[i]+0.3, hist[j,i],color="w",ha="center", va="center", fontweight="bold") #modificated

plt.colorbar(im, ax=ax)

输出:

在此处输入图像描述


推荐阅读