[英]How to add tooltips to a confusion matrix rendered via a Seaborn heatmap?
如何使我的 mat plot lib 具有交互性? 例如,當我將鼠標懸停在混淆矩陣的每個單元格上時,我想顯示該預測的實例。
confusion_mat_df = pd.DataFrame(confusion_mat,columns = pred_spectrum, index = actual_spectrum)
plt.figure(figsize=(7,5)) # width,height
sns.heatmap(confusion_mat_df, annot=True)
這是一個示例,用於說明如何將mplcursors用於 sklearn 混淆矩陣。
不幸的是,mplcursors 不適用於 seaborn 熱圖。 Seaborn 使用QuadMesh
作為熱圖,它不支持必要的坐標拾取。
在下面的代碼中,我在單元格的中心添加了置信度,類似於 seaborn 的。 我還更改了文本和箭頭的顏色以使其更易於閱讀。 您需要根據您的情況調整顏色和尺寸。
from sklearn.metrics import confusion_matrix
from matplotlib import pyplot as plt
import mplcursors
y_true = ["cat", "ant", "cat", "cat", "ant", "bird", "dog"]
y_pred = ["ant", "ant", "cat", "cat", "ant", "cat", "dog"]
labels = ["ant", "bird", "cat", "dog"]
confusion_mat = confusion_matrix(y_true, y_pred, labels=labels)
fig, ax = plt.subplots()
heatmap = plt.imshow(confusion_mat, cmap="jet", interpolation='nearest')
for x in range(len(labels)):
for y in range(len(labels)):
ax.annotate(str(confusion_mat[x][y]), xy=(y, x),
ha='center', va='center', fontsize=18, color='white')
plt.colorbar(heatmap)
plt.xticks(range(len(labels)), labels)
plt.yticks(range(len(labels)), labels)
plt.ylabel('Predicted Values')
plt.xlabel('Actual Values')
cursor = mplcursors.cursor(heatmap, hover=True)
@cursor.connect("add")
def on_add(sel):
i, j = sel.target.index
sel.annotation.set_text(f'{labels[i]} - {labels[j]} : {confusion_mat[i, j]}')
sel.annotation.set_fontsize(12)
sel.annotation.get_bbox_patch().set(fc="papayawhip", alpha=0.9, ec='white')
sel.annotation.arrow_patch.set_color('white')
plt.show()
PS:注解可以是多行的,例如:
sel.annotation.set_text(f'Predicted: {labels[i]}\nActual: {labels[j]}\n{confusion_mat[i, j]:5}')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.