首页 > 解决方案 > Matplotlib matshow 一个矩阵热图,一维比另一个大得多

问题描述

我正在使用 matplotlib matshow 来显示N*F. whereN可以是一个非常大的数字,例如5000but Fis only 10or 100

使用 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()

标签: pythonmatplotlib

解决方案


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

aa = np.random.random(size=(5, 500))
plt.imshow(aa, aspect='auto')

# equivalent:
# plt.matshow(aa, fignum=0, aspect='auto')

结果是:

在此处输入图像描述


推荐阅读