简体   繁体   中英

change seaborn scatter plot legend from number to text

Here is how I plot the decision boundary of my SVC` classifier.

X, y = make_classification(n_samples=100, n_features=2, n_redundant=0,
    n_clusters_per_class=1, weights=[0.9], flip_y=0, random_state=1)

# fit svm model 
svc_model = SVC(kernel='linear', random_state=32)
svc_model.fit(X, y)

# Constructing hyperplane using a formula.
w = svc_model.coef_[0]           
b = svc_model.intercept_[0]  
y_points = np.linspace(X[:, 1].min(), X[:, 1].max())
x_points = -(w[1] * y_points + b) / w[0]

# Plotting our two-features-space
sns.scatterplot(x=X[:, 0], y=X[:, 1], hue=y, s=50)

# Plotting a red hyperplane
plt.plot(x_points, y_points, c='r')

output:

在此处输入图像描述

OK, but I want to change the legend from [0,1] to ['cat', 'dog'] since that's what the labels represent.

EDIT

Using plt.legend() produces a legend with decision boundary as label: 在此处输入图像描述

Replace last line as...

plt.plot(x_points, y_points, c='r')
plt.legend(["Cat", "Dog"])

If you need the same shape, you will need to create custom legend. Show below...

ax=plt.plot(x, y, c='r')

from matplotlib.lines import Line2D

custom = [Line2D([], [], marker='.', color='blue', linestyle='None'),
          Line2D([], [], marker='.', color='orange', linestyle='None')]

plt.legend(custom, ["Cat", "Dog"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM