【问题标题】:Matplotlib matshow a matrix heatmap with 1 dimension being much bigger than the otherMatplotlib matshow 一个矩阵热图,一维比另一个大得多
【发布时间】:2020-07-03 19:05:52
【问题描述】:

我正在使用 matplotlib matshow 来显示N*F 的矩阵。其中N 可以是一个非常大的数字,例如5000,但F 只是10100

使用 matshow 时,这会导致 F 维度折叠,因为它会尝试以相等的空间显示行和列。

我希望生成的 matshow 图像的行加宽,同时列缩小。

这是我正在渲染的矩阵的示例:

我希望能够通过拉伸来查看实际的行。然而,宽度可以折叠,因为我正在查看矩阵热图的整体模式。

我需要做什么才能看到下面的代码。更改 figsize 还不够好,因为我不知道要看到多少数据,并且在测试了不同的 figsize 之后,生成的热图仍然崩溃。

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import mpl_toolkits.axes_grid1
from typing import List, Iterator, Optional

def paint_features(
    matrix: np.ndarray,
    labels: Optional[List[str]] = None,
    title: Optional[str] = None,
    fig: Optional[plt.Figure] = None,
) -> None:
    # change so classes are vertical
    matrix = matrix.T
    if fig is None:
        fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    matrix_image = ax.matshow(matrix, cmap=plt.cm.Blues)
    divider = mpl_toolkits.axes_grid1.make_axes_locatable(ax)
    cax = divider.append_axes("right", size="1%", pad=0.05)
    fig.colorbar(matrix_image, cax=cax)
    ax.tick_params(axis='x', bottom=False, labelbottom=False)
    if labels:
        assert len(labels) == matrix.shape[1]
        ax.set_yticklabels([""] + labels)
    ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
    if title is not None:
        fig.suptitle(title)
    fig.tight_layout()


def show_features(
    matrix: np.ndarray, labels: Optional[List[str]] = None, title: Optional[str] = None
) -> None:
    with plt_figure() as fig:
        paint_features(matrix, labels, title, fig)
        plt.show()

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您可以使用imshowaspect='auto' 让绘图自动调整到轴的大小:

    aa = np.random.random(size=(5, 500))
    plt.imshow(aa, aspect='auto')
    
    # equivalent:
    # plt.matshow(aa, fignum=0, aspect='auto')
    

    结果:

    【讨论】:

    • @CMCDragonkai 检查我的编辑。您需要fignum=0matshow 将创建一个具有不同纵横比的新图形
    猜你喜欢
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多