如何在python matplotlib中添加适当的图例

如何在python matplotlib中添加适当的图例,python,matplotlib,Python,Matplotlib,以上是我的代码,简单地分散一个数据集,它一直工作良好,直到它成为传奇。 我想将每个类及其相关标记设置为图例,但我得到了以下结果,这对红色数据没有帮助: 正如我们所见,我们只有绿色的数据图例,而没有红色的: 我不想使用进行循环或任何奇怪的操作。 我见过类似的问题,但不知道如何解决它们。为什么不 classes=['1','-1'] colors = {1:'red',-1:'green'} fig, axs = plt.subplots(1,1,figsize=(10,10)) axs.set_

以上是我的代码,简单地分散一个数据集,它一直工作良好,直到它成为传奇。 我想将每个类及其相关标记设置为图例,但我得到了以下结果,这对红色数据没有帮助:

正如我们所见,我们只有绿色的数据图例,而没有红色的:

我不想使用
进行循环
或任何奇怪的操作。 我见过类似的问题,但不知道如何解决它们。

为什么不

classes=['1','-1']
colors = {1:'red',-1:'green'}
fig, axs = plt.subplots(1,1,figsize=(10,10))
axs.set_xlabel('X1')#Features
axs.set_ylabel('X2')#Features
axs.set_title('Scatter plot of Data Target VS Features')
plt.scatter(X[X.columns[0]],X[X.columns[1]],c=Y.map(colors),label=classes,cmap=Y.map(colors))
axs.grid(True)
legend1=axs.legend(['-1','1'],loc="lower left", title="CLass",frameon=False)
axs.add_artist(legend1)
plt.show()

它仍然提供相同的输出。
scatter_plot = plt.scatter(
    X[X.columns[0]],
    X[X.columns[1]],
    c=Y.map(colors),
    label=classes,
    cmap=Y.map(colors)
)

plt.legend(
    handles=scatter_plot.legend_elements()[0], 
    labels=classes,
    loc="lower left", 
    title="Class"
)