在 plt.imshow 上添加文字
add text on plt.imshow
我有两个ndarrays:垫子,标签
目前我显示 Mat:
plt.imshow(Mat, cmap='gray', vmin=0, vmax=1, interpolation='None')
labels与Mat的shape相同,lables[(i,j)]包含一个Mat[(i,j)]的label。
如何在每个像素上显示标签?
最简单的方法是使用 Seaborn 的 heatmap。当 annot=True
时,它将数据值打印到单元格中。但是 annot=
也可以是标签矩阵。在这种情况下,将打印格式设置为字符串 (fmt='s'
) 很重要。 annot_kws=
可以设置额外的关键字,例如字体大小或颜色。 x
和 yticklabels
可以合并到对 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 的情况下创建类似的东西。它可以很容易地适应从不同的矩阵打印字符串,还可以添加一个测试来根据单元格的暗度改变颜色。
我有两个ndarrays:垫子,标签 目前我显示 Mat:
plt.imshow(Mat, cmap='gray', vmin=0, vmax=1, interpolation='None')
labels与Mat的shape相同,lables[(i,j)]包含一个Mat[(i,j)]的label。 如何在每个像素上显示标签?
最简单的方法是使用 Seaborn 的 heatmap。当 annot=True
时,它将数据值打印到单元格中。但是 annot=
也可以是标签矩阵。在这种情况下,将打印格式设置为字符串 (fmt='s'
) 很重要。 annot_kws=
可以设置额外的关键字,例如字体大小或颜色。 x
和 yticklabels
可以合并到对 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 的情况下创建类似的东西。它可以很容易地适应从不同的矩阵打印字符串,还可以添加一个测试来根据单元格的暗度改变颜色。