2017-09-13 99 views
0

我通過在Jupyter筆記本中使用matplotlib和mlxtend從Iris數據集製作了SVM圖。我試圖讓物種名稱對劇情的傳說,而不是0,1和2。到目前爲止,我的代碼是:enter image description here將圖例名稱添加到matplotlib中的SVM圖中

我不能。

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) 
在該地塊

和結果找到如何用物種名稱(Iris-setosa,Iris-versicolor和Iris-virginica)取代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) 

回答

2
plot_decision_regions(X=X, 
         y=y, 
         clf=clf, 
         legend=2) 

plt.title('SVM Decision Region Boundary', size=16) 
L = plt.legend() 
L.get_texts()[0].set_text('A') 
L.get_texts()[1].set_text('B') 
L.get_texts()[2].set_text('C') 

enter image description here

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() 

輸出示例:

我所創造的熊貓數據框:

enter image description here

+0

如何確保圖例中出現的手柄的順序與標籤的順序相同? – ImportanceOfBeingErnest

+0

@ImportanceOfBeingErnest對不起,我沒有想到我更新了答案。 – Dark