python - 从矩阵制作二维直方图
问题描述
我是 python 初学者,我有一个无法解决的问题。我需要使用我在 txt 中获得的矩阵制作二维直方图,我也可以在 xls 中获得它。矩阵示例:
4.52 4.54 4.52 4.44 4.34 4.28
5.10 4.92 4.82 4.80 4.66 4.44
6.12 5.80 5.57 5.50 5.15 4.70
6.47 6.54 6.27 6.13 6.21 5.97
8.11 8.73 8.70 8.63 8.84 8.55
我可以在代码中得到它:
a = np.loadtxt('matrix.txt')
然后我会拥有它。所以我有一部分代码,它使一个直方图像一个例子,但我不明白如何在这里整合我的矩阵:
import matplotlib.pyplot as plt
n = 100000
x = np.random.standard_normal(n)
y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n)
xedges = np.linspace(-4, 4, 42)
yedges = np.linspace(-25, 25, 42)
hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
xidx = np.clip(np.digitize(x, xedges), 0, hist.shape[0]-1)
yidx = np.clip(np.digitize(y, yedges), 0, hist.shape[1]-1)
c = hist[xidx, yidx]
plt.scatter(x, y, c=c)
plt.show()
在这段代码的帮助下,我想使用我的矩阵制作直方图,但我不明白如何。我会很感激的。
解决方案
显示矩阵的最简单方法是通过 seaborn 的热图。它看起来像:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
a = np.array([[4.52, 4.54, 4.52, 4.44, 4.34, 4.28],
[5.10, 4.92, 4.82, 4.80, 4.66, 4.44],
[6.12, 5.80, 5.57, 5.50, 5.15, 4.70],
[6.47, 6.54, 6.27, 6.13, 6.21, 5.97],
[8.11, 8.73, 8.70, 8.63, 8.84, 8.55]])
sns.heatmap(a, annot=True, fmt='.2f', square=True)
plt.show()
由于这些值不是整数,也不是总和为 1 的浮点数,a
因此似乎不是直方图。
另一种方法是创建3D 图:
import matplotlib.pyplot as plt
import numpy as np
a = np.array([[4.52, 4.54, 4.52, 4.44, 4.34, 4.28],
[5.10, 4.92, 4.82, 4.80, 4.66, 4.44],
[6.12, 5.80, 5.57, 5.50, 5.15, 4.70],
[6.47, 6.54, 6.27, 6.13, 6.21, 5.97],
[8.11, 8.73, 8.70, 8.63, 8.84, 8.55]])
fig = plt.figure(figsize=plt.figaspect(0.5))
ax = fig.add_subplot(1, 1, 1, projection='3d')
xedges = np.arange(a.shape[1] + 1)
yedges = np.arange(a.shape[0] + 1)
# Construct arrays for the anchor positions of the 30 bars.
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25, indexing="ij")
xpos = xpos.ravel()
ypos = ypos.ravel()
zpos = 0
# Construct arrays with the dimensions for the 30 bars.
dx = dy = 0.5 * np.ones_like(zpos)
dz = a.ravel()
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, zsort='average', color='turquoise')
plt.show()
推荐阅读
- javascript - jQuery过滤多个数据属性
- java - (JAVA) 具有复杂输入参数的 Spark SQL UDF
- typescript - getElement 不是函数类型脚本
- javascript - 商店调度后VueJS发出不工作
- python-3.x - 如何使用 Python 提取 Workday 职位发布链接?
- python - 禁止 Django 直接分配到多对多集合的反面。使用 .set()
- laravel - 为什么我在使用 Laravel Websockets 包时遇到问题?
- c++ - 使用 nano.specs 时 libc.a 和 libc_nano.a 之间的多个函数定义
- javascript - msSaveBlob 文件损坏
- reactjs - 无法从我的 next.js 应用程序获取我的strapi 数据