python - 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。
解决方案
您放置索引是错误的。
你应该使用: 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)
输出:
推荐阅读
- typescript - 带有道具的基于动态类的组件
- swift - 点击视图时如何切换 SwiftUI 切换?
- reactjs - 如何在 Reactjs 客户端托管的 IFrame 中嵌入 oidc-client 登录/登录重定向
- docker - 如何从 docker 网络获取随机 IP?
- javascript - doc.ouput 的问题
- python - Python > Kivy > 如何更改 RecycleView 对象中的数据
- css - Grunt-Sass 如何防止 CSS 解压
- angular - 垫子徽章动态计数
- sql - ssis case语句派生列
- xml - 在 ListView 中加载 Xml 文件并编辑一些值