Python 将图例名称添加到matplotlib中的SVM绘图

Python 将图例名称添加到matplotlib中的SVM绘图,python,pandas,matplotlib,jupyter-notebook,Python,Pandas,Matplotlib,Jupyter Notebook,我使用Jupyter笔记本中的matplotlib和mlxtend从Iris数据集绘制了SVM图。我正在尝试获取该地块图例上的物种名称,而不是0、1和2。到目前为止,我的代码是: from sklearn import svm from mlxtend.plotting import plot_decision_regions X = iris[['SepalLengthCm', 'SepalWidthCm']] y = iris['SpecieID'] clf = svm.SVC(deci

我使用Jupyter笔记本中的matplotlib和mlxtend从Iris数据集绘制了SVM图。我正在尝试获取该地块图例上的物种名称,而不是0、1和2。到目前为止,我的代码是:

from sklearn import svm
from mlxtend.plotting import plot_decision_regions

X = iris[['SepalLengthCm', 'SepalWidthCm']]
y = iris['SpecieID']

clf = svm.SVC(decision_function_shape = 'ovo')
clf.fit(X.values, y.values) 

# Plot Decision Region using mlxtend's awesome plotting function
plot_decision_regions(X=X.values, 
                      y=y.values,
                      clf=clf, 
                      legend=2)

# Update plot object with X/Y axis labels and Figure Title
plt.xlabel(X.columns[0], size=14)
plt.ylabel(X.columns[1], size=14)
plt.title('SVM Decision Region Boundary', size=16)
结果如下:

我找不到如何用物种名称(刚毛鸢尾、花色鸢尾和弗吉尼亚鸢尾)替换0、1和2

我通过以下方式创建了熊猫数据帧:

import pandas as pd
iris = pd.read_csv("Iris.csv") # the iris dataset is now a Pandas DataFrame
iris = iris.assign(SepalRatio = iris['SepalLengthCm'] / iris['SepalWidthCm']).assign(PetalRatio = iris['PetalLengthCm'] / iris['PetalWidthCm']).assign(SepalMultiplied = iris['SepalLengthCm'] * iris['SepalWidthCm']).assign(PetalMultiplied = iris['PetalLengthCm'] * iris['PetalWidthCm'])
d = {"Iris-setosa" : 0, "Iris-versicolor": 1, "Iris-virginica": 2}
iris['SpecieID'] = iris['Species'].map(d).fillna(-1)


另一个,借助当前打印轴的手柄和标签,即

handles, labels =  plt.gca().get_legend_handles_labels()
plt.legend(handles, list(map(d.get, [int(i) for i in labels])) , loc= 'upper left') #Map the values of current labels with dictionary and pass it as labels parameter. 
plt.show()
样本输出:


另一个,借助当前打印轴的手柄和标签,即

handles, labels =  plt.gca().get_legend_handles_labels()
plt.legend(handles, list(map(d.get, [int(i) for i in labels])) , loc= 'upper left') #Map the values of current labels with dictionary and pass it as labels parameter. 
plt.show()
样本输出:


在@Dark answer之后,这里是一个完整的代码以及突出显示的支持向量

from mlxtend.plotting import plot_decision_regions
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.svm import SVC

# Loading some example data
iris = datasets.load_iris()
X = iris.data[:, [0, 2]]
y = iris.target

# In case if the original data categories name were present 
# then we replace them with numbers
d = {"Iris-setosa" : 0, "Iris-versicolor": 1, "Iris-virginica": 2} 

# Training a classifier
svm = SVC(C=0.5, kernel='linear')
svm.fit(X, y)


# Plotting decision regions
plt.figure(figsize=(8,6))
plot_decision_regions(X, y, clf=svm, legend=2, X_highlight=svm.support_vectors_)

# Adding legend 
handles, labels =  plt.gca().get_legend_handles_labels()
d_rev = {y:x for x,y in d.items()} # switching key-value pairs
plt.legend(handles, list(map(d_rev.get, [int(i) for i in d_rev])))

# Adding axes annotations
plt.xlabel('sepal length [cm]')
plt.ylabel('petal length [cm]')
plt.title('SVM on Iris')
plt.show()

在@Dark answer之后,这里是一个完整的代码以及突出显示的支持向量

from mlxtend.plotting import plot_decision_regions
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.svm import SVC

# Loading some example data
iris = datasets.load_iris()
X = iris.data[:, [0, 2]]
y = iris.target

# In case if the original data categories name were present 
# then we replace them with numbers
d = {"Iris-setosa" : 0, "Iris-versicolor": 1, "Iris-virginica": 2} 

# Training a classifier
svm = SVC(C=0.5, kernel='linear')
svm.fit(X, y)


# Plotting decision regions
plt.figure(figsize=(8,6))
plot_decision_regions(X, y, clf=svm, legend=2, X_highlight=svm.support_vectors_)

# Adding legend 
handles, labels =  plt.gca().get_legend_handles_labels()
d_rev = {y:x for x,y in d.items()} # switching key-value pairs
plt.legend(handles, list(map(d_rev.get, [int(i) for i in d_rev])))

# Adding axes annotations
plt.xlabel('sepal length [cm]')
plt.ylabel('petal length [cm]')
plt.title('SVM on Iris')
plt.show()

您如何确保句柄在图例中的显示顺序与标签的顺序相同?@ImportanceOfBeingErnest抱歉没有想到我更新了答案。您如何确保句柄在图例中的显示顺序与标签的顺序相同?@ImportanceOfBeingErnest抱歉因为没有想到这一点,我更新了答案。