【问题标题】:Isometric orientation for heatmap with matplotlib使用 matplotlib 的热图的等距方向
【发布时间】:2021-11-08 04:14:46
【问题描述】:

假设我们有如下的热图

使用代码构建

import string
import numpy as np
from matplotlib import pyplot as plt
label=list(string.ascii_uppercase)
mdata = np.random.randn(3, len(label), len(label))
data = mdata[0, :, :]
data=np.tril(data,-1)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)
plt.show()

无论是使用 Matplotlib、Seaborn 还是任何其他包都可以渲染成等距 对齐方式如下。

【问题讨论】:

    标签: python matplotlib seaborn isometric


    【解决方案1】:

    使用 matplotlib 的 3D toolkit 和 numpy 的 triu_indices,您可以从三角矩阵创建条形图:

    import numpy as np
    import matplotlib.pyplot as plt
    
    ax = plt.figure().add_subplot(projection='3d')
    N = 26
    data = np.random.randn(3, N, N)
    for i, (plane, cmap) in enumerate(zip(data, ['Reds', 'Greens', 'Blues'])):
        indices = np.triu_indices(N, 1)
        norm = plt.Normalize(plane.min(), plane.max())
        ax.bar(left=indices[0], bottom=indices[1], height=0.9,
               zs=i, zdir='y',
               color=plt.get_cmap(cmap)(norm(plane[indices])))
    plt.show()
    

    PS:为了得到完整的矩形,np.indices 的子数组需要被做成一维的:

    import numpy as np
    import matplotlib.pyplot as plt
    
    ax = plt.figure().add_subplot(projection='3d')
    N = 26
    data = np.random.randn(3, N, N)
    for i, (plane, cmap) in enumerate(zip(data, ['Reds', 'Greens', 'Blues'])):
        indices = np.indices((N,N))
        norm = plt.Normalize(plane.min(), plane.max())
        ax.bar(left=indices[0].ravel(), bottom=indices[1].ravel(), height=0.9,
               zs=i, zdir='y',
               color=plt.get_cmap(cmap)(norm(plane).ravel()))
    plt.show()
    

    【讨论】:

    • 太棒了。为了未来的读者和我的利益(这里有点贪心)。你介意分享绘制完整数组的sn-p吗(OP图中显示的上下tri)
    • 嗨@JohanC,我将triu_indices 更改为np.indices((N, N)),但是没有成功。请指教
    猜你喜欢
    • 2014-05-07
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    相关资源
    最近更新 更多