如何使用 matplotlib(或其他 lib/tool)创建六边形热图
How to create a hexagonal heat map using matplotlib(or other lib/tool)
我有一个二维数组,其中包含每个单元的热度。
用方形单位画二维热图很容易,但是用六边形怎么画呢
为什么我需要这个?
SOM(a learning algrithomn) 输出六边形神经元网络。我可以从训练好的模型中得到距离图(U-Matrix,2D 矩阵)。
matpyplot中的hexbin
函数或seaborn中的jointplot(kind="hex")
函数只计算每个点的频率。输入参数是 x
和 y
。但是我有一个 2D Array 有权重(或者说,颜色深度,我想画的)。
例如,我不知道他是如何实现的
简而言之,您需要提供将二维数组映射到 matplotlib 的 hexbin
函数的网格坐标。您可以通过多种方式制作这些网格,包括编写您自己的函数,但也许最好的方式就是使用 np.meshgrid
。请注意,传递给 hexbin
函数的 X、Y 和 C 参数都必须是一维数组。
A = np.random.random((10, 10))
X, Y = np.meshgrid(range(A.shape[0]), range(A.shape[-1]))
X, Y = X*2, Y*2
# Turn this into a hexagonal grid
for i, k in enumerate(X):
if i % 2 == 1:
X[i] += 1
Y[:,i] += 1
fig, ax = plt.subplots()
im = ax.hexbin(
X.reshape(-1),
Y.reshape(-1),
C=A.reshape(-1),
gridsize=int(A.shape[0]/2)
)
# the rest of the code is adjustable for best output
ax.set_aspect(0.8)
ax.set(xlim=(-4, X.max()+4,), ylim=(-4, Y.max()+4))
ax.axis(False)
plt.colorbar(im)
plt.show()
这给出:
我有一个二维数组,其中包含每个单元的热度。 用方形单位画二维热图很容易,但是用六边形怎么画呢
为什么我需要这个? SOM(a learning algrithomn) 输出六边形神经元网络。我可以从训练好的模型中得到距离图(U-Matrix,2D 矩阵)。
matpyplot中的hexbin
函数或seaborn中的jointplot(kind="hex")
函数只计算每个点的频率。输入参数是 x
和 y
。但是我有一个 2D Array 有权重(或者说,颜色深度,我想画的)。
例如,我不知道他是如何实现的
简而言之,您需要提供将二维数组映射到 matplotlib 的 hexbin
函数的网格坐标。您可以通过多种方式制作这些网格,包括编写您自己的函数,但也许最好的方式就是使用 np.meshgrid
。请注意,传递给 hexbin
函数的 X、Y 和 C 参数都必须是一维数组。
A = np.random.random((10, 10))
X, Y = np.meshgrid(range(A.shape[0]), range(A.shape[-1]))
X, Y = X*2, Y*2
# Turn this into a hexagonal grid
for i, k in enumerate(X):
if i % 2 == 1:
X[i] += 1
Y[:,i] += 1
fig, ax = plt.subplots()
im = ax.hexbin(
X.reshape(-1),
Y.reshape(-1),
C=A.reshape(-1),
gridsize=int(A.shape[0]/2)
)
# the rest of the code is adjustable for best output
ax.set_aspect(0.8)
ax.set(xlim=(-4, X.max()+4,), ylim=(-4, Y.max()+4))
ax.axis(False)
plt.colorbar(im)
plt.show()
这给出: