【问题标题】:add text on plt.imshow在 plt.imshow 上添加文本
【发布时间】:2020-09-12 15:09:33
【问题描述】:

我有两个 ndarray:垫子、标签 目前我显示 Mat:

plt.imshow(Mat, cmap='gray', vmin=0, vmax=1, interpolation='None')

labels 与 Mat 具有相同的形状,而 labels[(i,j)] 包含 Mat[(i,j)] 的标签。 如何在每个像素上显示标签?

【问题讨论】:

    标签: matplotlib imshow


    【解决方案1】:

    最简单的方法是使用 Seaborn 的 heatmap。当annot=True 时,它将数据值打印到单元格中。但annot= 也可以是标签矩阵。在这种情况下,将打印格式设置为字符串 (fmt='s') 很重要。 annot_kws= 可以设置额外的关键字,例如字体大小或颜色。 xyticklabels 可以合并到对 heatmap() 的调用中,或者在之后使用 matplotlib 设置。

    默认着色的一个重要好处是 Sorn 在浅色单元格上使用黑色,在深色单元格上使用白色。

    这是一个使用一些 utf8 字符作为标签的示例。

    from matplotlib import pyplot as plt
    import numpy as np
    import seaborn as sns
    
    M, N = 5, 10
    mat = np.random.rand(M, N)
    labels = np.random.choice(['X', '☀', '★', '♛'], size=(M, N))
    ax = sns.heatmap(mat, cmap="inferno", annot=labels, annot_kws={'fontsize': 16}, fmt='s')
    plt.show()
    

    PS:文档中有一个matplotlib example 可以在没有 Seaborn 的情况下创建类似的东西。它可以很容易地适应打印来自不同矩阵的字符串,还可以添加一个测试来根据单元格的暗度改变颜色。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      • 2012-07-31
      • 2020-11-01
      • 2023-04-03
      • 2021-03-21
      • 2023-01-05
      • 1970-01-01
      相关资源
      最近更新 更多