如何使用matplotlib(或其他库/工具)创建六边形热图

2024-05-19 08:59:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个2D数组,包含每个单元的热量。 用正方形单位绘制二维热图很容易,但如何用六边形绘制热图呢


为什么我需要这个? SOM(一种学习算法)输出一个六边形神经元网络。我可以从训练过的模型中得到一个距离图(U矩阵,2D矩阵)


matpyplot中的hexbin函数或seaborn中的jointplot(kind="hex")函数仅统计每个点的频率。输入参数是xy。但我拥有的是一个带有权重(或者说,我想画的颜色深度)的2D数组


例如,我不知道他是如何实现的 example, I don't konw how he implements it


Tags: 函数模型算法距离绘制单位矩阵数组
1条回答
网友
1楼 · 发布于 2024-05-19 08:59:17

简而言之,您需要提供二维数组映射到matplotlib的hexbin函数的网格坐标。您可以通过多种方式创建这些网格,包括编写自己的函数,但最好的方法可能是只使用np.meshgrid。请注意,传递给hexbin函数的X、Y和C参数都必须是1d数组

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()
ax.hexbin(
    X.reshape(-1), 
    Y.reshape(-1), 
    C=A.reshape(-1), 
    gridsize=A.shape[0]
)

# 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.show()

这使得:

enter image description here

相关问题 更多 >

    热门问题