如何在子图中将图例设置为 matplotlib 轴

how to set legend to a matplolib Axes in a subfigure plot

我正在尝试使用 iris 数据集绘制 SVM classifier 的决策边界。尽管我设置了 label=y.

,但 class 标签并未出现在图例中

代码:

import matplotlib.pyplot as plt 
from sklearn import svm, datasets 
from sklearn.inspection import DecisionBoundaryDisplay

iris = datasets.load_iris()
X = iris.data[:, :2]
y = iris.target

linear = svm.LinearSVC()
linear.fit(X,y)

X0, X1 = X[:, 0], X[:, 1]

fig, ax = plt.subplots(figsize=(10, 6))
disp = DecisionBoundaryDisplay.from_estimator(linear, X,
    response_method='predict',cmap=plt.cm.coolwarm, alpha=.8,ax=ax,
    xlabel=iris.feature_names[0],ylabel=iris.feature_names[1],label=y)
ax.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')
ax.set_xticks(())
ax.set_yticks(())
ax.set_title('Some title') 
ax.legend()
plt.show()

图:

运行 你的代码我收到这个警告:

UserWarning: The following kwargs were not used by contour: 'label'

这是由于将label=y传递给disp = DecisionBoundaryDisplay.from_estimator

造成的

如果你想显示图例,我建议使用散点图,如下所示:

disp = DecisionBoundaryDisplay.from_estimator(linear, X,
    response_method='predict',cmap=plt.cm.coolwarm, alpha=.8,ax=ax,
    xlabel=iris.feature_names[0],ylabel=iris.feature_names[1])

classes = sorted(list(set(y)))
for c in classes:
    ax.scatter(X0[y == c], X1[y == c], color=plt.cm.coolwarm(c / max(classes)), s=20, edgecolors='k', label=c)

你可以使用 automatic legend creation。你的情况:

scatter = ax.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k',
           )
legend1 = ax.legend(*scatter.legend_elements(),
                    loc="lower left", title="Classes")
ax.add_artist(legend1)

产生: