将 seaborn 散点图图例从数字更改为文本

change seaborn scatter plot legend from number to text

下面是我如何绘制 SVC` 分类器的决策边界。

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

输出:

好的,但我想将图例从 [0,1] 更改为 ['cat', 'dog'],因为这就是标签所代表的内容。

编辑

使用 plt.legend() 生成以决策边界作为标签的图例:

将最后一行替换为...

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

如果您需要相同的形状,则需要创建自定义图例。显示如下...

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"])