简体   繁体   English

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

[英]how to set label for each subplot in a plot in matplotlib?

let's think i have four features in a dataset and plotting scatter plots using two features each time.I want to provide label to each plot separately. 假设我在数据集中有四个要素,并且每次都使用两个要素绘制散点图。我想分别为每个图提供标签。

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

在此处输入图片说明

Here I will get two scatter plots but labels are not shown. 在这里,我将获得两个散点图,但未显示标签。 I want to see admitted as label for first plot and not-admitted for second scatter plot. 我想看到被允许作为第一个散点图的标签,而不被允许作为第二个散点图的标签。

I am able to give label by using plt.legend() but not getting already created plots. 我可以通过使用plt.legend()来给标签,但不能获取已经创建的图。

You are setting the label for the axes, not the scatters. 您正在设置轴的标签,而不是散布的标签。

The most convenient way to get a legend entry for a plot is to use the label argument. 获取图例条目的最便捷方法是使用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()

If you want to set the label after creating the scatter, but before creating the legend, you may use set_label on the PathCollection returned by the scatter 如果你想设置标签制作散射后,却创造了传奇之前,你可以使用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()

Finally you may set the labels within the legend call: 最后,您可以在图例调用中设置标签:

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

In all three cases, the result will look like this: 在这三种情况下,结果都将如下所示:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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