繁体   English   中英

来自数据文件的 2D 直方图 plot

[英]2D histogram plot from data file

如何从给定的二维 numpy 数组中制作二维直方图(或曲面)plot,其中第一个索引是“x”维度的 label,“y”维度的第二个索引,第三个是要计算的值密谋? 例子:

[[4.80000e+01 5.12000e+02 8.03447e+03]
 [4.80000e+01 2.56000e+02 9.24963e+03]
 [4.80000e+01 1.28000e+02 9.02154e+03]
 [4.80000e+01 6.40000e+01 8.96437e+03]
 [4.80000e+01 3.20000e+01 7.98477e+03]
 [4.80000e+01 1.60000e+01 1.07688e+04]
 [4.80000e+01 8.00000e+00 1.96227e+04]
 [4.80000e+01 4.00000e+00 3.51944e+04]
 [5.20000e+01 5.12000e+02 7.53994e+03]
 [5.20000e+01 2.56000e+02 7.54521e+03]
 [5.20000e+01 1.28000e+02 8.12631e+03]
 [5.20000e+01 6.40000e+01 8.12542e+03]
 [5.20000e+01 3.20000e+01 7.49664e+03]
 [5.20000e+01 1.60000e+01 9.92450e+03]
 ...

要绘制的整个二维区域是 (18,8)。

由于 matplotlib 似乎接受二维数组(网格/轮廓)中的数据,我试图首先将值填充到新创建的带有循环的二维 numpy 数组中,但无法查找索引。

xlu=np.unique(d[:,0])
ylu=np.unique(d[:,1])

z=np.empty((xdim,ydim))

for x in d:
    z[ np.where(xlu==x[0])[0] , np.where(ylu==x[1])[0] ] = z[2]

有没有更快/更优雅的方法来获得二维直方图/表面 plot?

plt.tricontourf(d[:,0], d[:,1], d[:,2])从未组织为网格的xyz数据创建填充轮廓。

plt.hist2d(d[:,0], d[:,1], weights=d[:,2])创建一个二维直方图,其中每个x,y的权重由z给出。

from matplotlib import pyplot as plt
import numpy as np

d = np.random.randn(1000, 10, 3).cumsum(axis=0).reshape(-1, 3)

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 4))

sm1 = ax1.tricontourf(d[:, 0], d[:, 1], d[:, 2], cmap='hot')
plt.colorbar(sm1, ax=ax1)
ax1.set_title('plt.tricontourf()')

_, _, _, sm2 = ax2.hist2d(d[:, 0], d[:, 1], weights=d[:, 2], bins=40, cmap='hot')
ax2.set_title('plt.hist2d()')
plt.colorbar(sm2, ax=ax2)

plt.tight_layout()
plt.show()

示例图

似乎您需要对数据进行插值,因为它是不规则间隔的。

这是官方文档( 链接)中的一个片段。

import matplotlib.tri as tri
import numpy as np

np.random.seed(19680801)
npts = 200
ngridx = 100
ngridy = 200
x = np.random.uniform(-2, 2, npts)
y = np.random.uniform(-2, 2, npts)
z = x * np.exp(-x**2 - y**2)

fig, (ax1, ax2) = plt.subplots(nrows=2)

# -----------------------
# Interpolation on a grid
# -----------------------
# A contour plot of irregularly spaced data coordinates
# via interpolation on a grid.

# Create grid values first.
xi = np.linspace(-2.1, 2.1, ngridx)
yi = np.linspace(-2.1, 2.1, ngridy)

# Linearly interpolate the data (x, y) on a grid defined by (xi, yi).
triang = tri.Triangulation(x, y)
interpolator = tri.LinearTriInterpolator(triang, z)
Xi, Yi = np.meshgrid(xi, yi)
zi = interpolator(Xi, Yi)

# Note that scipy.interpolate provides means to interpolate data on a grid
# as well. The following would be an alternative to the four lines above:
#from scipy.interpolate import griddata
#zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='linear')

ax1.contour(xi, yi, zi, levels=14, linewidths=0.5, colors='k')

它本质上是做什么的,它使用三线性插值将 function 的值插值到规则网格中。 根据您的目标,还有其他方法可以做到这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM