如何获得用 plt.matshow 和彩色网格绘制的字符串数组?

How to get an array of strings plotted with plt.matshow and a colored mesh grid?

我有这种数据(字符串数组)

data = [['x', '1', '0'],['x', '1', 'x'],['0', '0', '1']]

我想要类似于此代码片段的内容

import matplotlib.pyplot as plt
import numpy as np

# a 2D array with linearly increasing values on the diagonal
a = np.diag(range(15))

plt.matshow(a)

plt.show()

具有以下详细信息:

感谢任何帮助!

您可以按如下方式组合 np.unique()ListedColormap

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np

data = [['x', '1', '0'], ['x', '1', 'x'], ['0', '0', '1']]
data = np.array(data)
unique_chars, matrix = np.unique(data, return_inverse=True)
color_dict = {'x': 'darkred', '1': 'white', '0': 'orange'}
plt.matshow(matrix.reshape(data.shape), cmap=ListedColormap([color_dict[char] for char in unique_chars]))
plt.xticks(np.arange(data.shape[1]), np.arange(data.shape[1]) + 1)
plt.yticks(np.arange(data.shape[0]), np.arange(data.shape[0]) + 1)
plt.show()

你也可以试试 seaborn 的热图:

import seaborn as sns

sns.set(font_scale=2)
ax = sns.heatmap(matrix.reshape(data.shape), annot=data, annot_kws={'fontsize': 30}, fmt='',
                 linecolor='dodgerblue', lw=5, square=True, clip_on=False,
                 cmap=ListedColormap([color_dict[char] for char in unique_chars]),
                 xticklabels=np.arange(data.shape[1]) + 1, yticklabels=np.arange(data.shape[0]) + 1, cbar=False)
ax.tick_params(labelrotation=0)