如何在 Matplotlib 中捕獲拾取事件並用它來啟用或停用線圖


在 Matplotlib 中啟用繪圖物件的拾取事件屬性後,任務是使用拾取事件啟用和停用給定軸上的一組繪圖中的線圖。

為了拾取特定的線圖,我們使用圖例。

我們將使用二元分類圖來建立 ROC 曲線。ROC 曲線或受試者工作特徵曲線用於診斷、天氣預報和其他應用。它包含**真陽性率 (TPR)** 和**假陽性率 (FPR)**。使用 ROC,我們將建立該曲線的多個圖。

讓我們首先匯入庫。這裡使用“nbAgg”來啟用互動式圖形。

import matplotlib.pyplot as plt
plt.switch_backend('nbAgg')
import pandas as pd

現在從資料或 Excel 檔案中讀取“fpr(假陽性率)”和“tpr(真陽性率)”。為了演示,它將如下所示:

fpr_logreg = pd.read_excel('ROC_Curves.xlsx', 'fpr_logreg')
tpr_logreg = pd.read_excel('ROC_Curves.xlsx', 'tpr_logreg')
fpr_KNN = pd.read_excel('ROC_Curves.xlsx', 'fpr_KNN')
tpr_KNN = pd.read_excel('ROC_Curves.xlsx', 'tpr_KNN')
fpr_MLP = pd.read_excel('ROC_Curves.xlsx', 'fpr_MLP')
tpr_MLP = pd.read_excel('ROC_Curves.xlsx', 'tpr_MLP')
fpr_SGD = pd.read_excel('ROC_Curves.xlsx', 'fpr_SGD')
tpr_SGD = pd.read_excel('ROC_Curves.xlsx', 'tpr_SGD')
fpr_GNB = pd.read_excel('ROC_Curves.xlsx', 'fpr_GNB')
tpr_GNB = pd.read_excel('ROC_Curves.xlsx', 'tpr_GNB')
fpr_svc = pd.read_excel('ROC_Curves.xlsx', 'fpr_svc')
tpr_svc = pd.read_excel('ROC_Curves.xlsx', 'tpr_svc')
fpr_RF = pd.read_excel('ROC_Curves.xlsx', 'fpr_RF')
tpr_RF = pd.read_excel('ROC_Curves.xlsx', 'tpr_RF')
fpr_DT = pd.read_excel('ROC_Curves.xlsx', 'fpr_DT')
tpr_DT = pd.read_excel('ROC_Curves.xlsx', 'tpr_DT')

現在定義並建立具有空網格的圖形:

fig = plt.figure(figsize=(10,8))

為給定資料繪製線圖:

plt.plot([0, 1], [0, 1], 'k--')
l1, = plt.plot(fpr_logreg, tpr_logreg, label='LogReg',color='purple')
l2, = plt.plot(fpr_KNN, tpr_KNN, label='KNN',color='green')
l3, = plt.plot(fpr_DT, tpr_DT, label='DecisionTree', color='orange')
l4, = plt.plot(fpr_RF, tpr_RF, label='Random Forest',color='yellow')
l5, = plt.plot(fpr_MLP, tpr_MLP, label='MLP',color='red')
l6, = plt.plot(fpr_svc, tpr_svc, label='SVC',color='violet')
l7, = plt.plot(fpr_GNB, tpr_GNB, label='GNB',color='grey')
l8, = plt.plot(fpr_SGD, tpr_SGD, label='SGD', color='pink')

設定圖的標籤、圖例和標題:

plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC curve')
lgd = plt.legend(loc='lower right', fancybox=True, shadow=True)

現在將圖例與其標籤對映:

pltlines = [l1, l2, l3, l4, l5, l6, l7, l8]
leg_ln_map = dict()
for leg_line, plot_line in zip(lgd.get_lines(), pltlines):
leg_line.set_picker(10)
leg_ln_map[leg_line] = plot_line

定義回撥函式以響應拾取事件:

示例

def on_pick(event):
# on the pick event, find the plot line corresponding to the legend line, and toggle the visibility
   leg_line = event.artist
   plot_line = leg_ln_map[leg_line]
   vis = not plot_line.get_visible()
   plot_line.set_visible(vis)
# Change the alpha on the line in the legend so we can see what lines have been toggled
   if vis:
      leg_line.set_alpha(1.0)
   else:
      leg_line.set_alpha(0.2)
      fig.canvas.draw()

現在將事件與回撥函式連線:

fig.canvas.mpl_connect('pick_event', onpick)

顯示建立的圖的輸出:

plt.show()

輸出

更新於:2021 年 2 月 23 日

452 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.