如何在matplotlib中为图中的每个子图设置标签?

ram*_*ddy 6 python data-visualization matplotlib

让我们认为我在数据集中有四个特征,并且每次使用两个特征绘制散点图。我想分别为每个图提供标签。

fig,axes=plt.subplots(ncols=2,figsize=(10,8))
axes[0].scatter(x1,x2],marker="o",color="r")
axes[1].scatter(x3,x4,marker="x",color="k")
axes[0].set(xlabel="Exam score-1",ylabel="Exam score-2")
axes[1].set(xlabel="Exam score-1",ylabel="Exam score-2")
axes[0].set_label("Admitted")
axes[1].set_label("Not-Admitted")
axes.legend()
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

在这里,我将得到两个散点图,但未显示标签。我想看到第一个图被承认为标签 ,第二个散点图不被承认

我可以通过使用plt.legend()但无法获取已创建的图来提供标签。

Imp*_*est 11

您正在为轴设置标签,而不是散点。

获取图例的图例条目最方便的方法是使用label参数。

import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.rand(2,23)

fig,axes=plt.subplots(ncols=2)
axes[0].scatter(x,y, marker="o", color="r", label="Admitted")
axes[1].scatter(x,y, marker="x", color="k", label="Not-Admitted")
axes[0].set(xlabel="Exam score-1", ylabel="Exam score-2")
axes[1].set(xlabel="Exam score-1", ylabel="Exam score-2")

axes[0].legend()
axes[1].legend()
plt.show()
Run Code Online (Sandbox Code Playgroud)

如果你想在创建散点后设置标签,但在创建图例之前,你可以使用set_labelPathCollection返回的scatter

import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.rand(2,23)

fig,axes=plt.subplots(ncols=2)
sc1 = axes[0].scatter(x,y, marker="o", color="r")
sc2 = axes[1].scatter(x,y, marker="x", color="k")
axes[0].set(xlabel="Exam score-1", ylabel="Exam score-2")
axes[1].set(xlabel="Exam score-1", ylabel="Exam score-2")

sc1.set_label("Admitted")
sc2.set_label("Not-Admitted")

axes[0].legend()
axes[1].legend()
plt.show()
Run Code Online (Sandbox Code Playgroud)

最后,您可以在图例调用中设置标签:

import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.rand(2,23)

fig,axes=plt.subplots(ncols=2)
sc1 = axes[0].scatter(x,y, marker="o", color="r")
sc2 = axes[1].scatter(x,y, marker="x", color="k")
axes[0].set(xlabel="Exam score-1", ylabel="Exam score-2")
axes[1].set(xlabel="Exam score-1", ylabel="Exam score-2")

axes[0].legend([sc1], ["Admitted"])
axes[1].legend([sc2], ["Not-Admitted"])
plt.show()
Run Code Online (Sandbox Code Playgroud)

在所有三种情况下,结果将如下所示:

在此处输入图片说明