[英]how to set label for each subplot in a plot in 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()
在這里,我將獲得兩個散點圖,但未顯示標簽。 我想看到被允許作為第一個散點圖的標簽,而不被允許作為第二個散點圖的標簽。
我可以通過使用plt.legend()
來給標簽,但不能獲取已經創建的圖。
您正在設置軸的標簽,而不是散布的標簽。
獲取圖例條目的最便捷方法是使用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()
如果你想設置標簽制作散射后,卻創造了傳奇之前,你可以使用set_label
在PathCollection
通過返回的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()
最后,您可以在圖例調用中設置標簽:
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()
在這三種情況下,結果都將如下所示:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.