我有這種資料(字串陣列)
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()
具有以下詳細資訊:
- 'x' 是深紅色的
- '1' 是白色的
- '0' 是橙色的
- 像素之間的彩色網格
- 從 1 開始刻度
任何幫助表示贊賞!
uj5u.com熱心網友回復:
您可以組合np.unique()和 aListedColormap如下:
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)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/433232.html
標籤:Python 数组 matplotlib
