[英]Matplotlib legends in subplot
I would like to put legends inside each one of the subplots below.我想在下面的每个子图中放置图例。 I've tried with plt.legend but it didn't work.我试过 plt.legend 但没有用。
Any suggestions?有什么建议?
Thanks in advance :-)提前致谢 :-)
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
ax1.plot(xtr, color='r', label='Blue stars')
ax2.plot(ytr, color='g')
ax3.plot(ztr, color='b')
ax1.set_title('2012/09/15')
plt.legend([ax1, ax2, ax3],["HHZ 1", "HHN", "HHE"])
plt.show()
With the suggestion from atomh33ls:根据 atomh33ls 的建议:
ax1.legend("HHZ 1",loc="upper right")
ax2.legend("HHN",loc="upper right")
ax3.legend("HHE",loc="upper right")
The legend position is fixed, however it seems to have a problem with the strings, because each letter is placed in a new line.图例位置是固定的,但是字符串似乎有问题,因为每个字母都放在一个新行中。
Does anyone knows how to fix it?有谁知道如何解决它?
This should work:这应该有效:
ax1.plot(xtr, color='r', label='HHZ 1')
ax1.legend(loc="upper right")
ax2.plot(xtr, color='r', label='HHN')
ax2.legend(loc="upper right")
ax3.plot(xtr, color='r', label='HHE')
ax3.legend(loc="upper right")
What you want cannot be done, because plt.legend()
places a legend in the current axes , in your case in the last one.您想要的无法完成,因为plt.legend()
在当前轴中放置了一个图例,在您的情况下是在最后一个中。
If, on the other hand, you can be content with placing a comprehensive legend in the last subplot, you can do like this另一方面,如果您可以满足于在最后一个子情节中放置一个全面的图例,您可以这样做
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
l1,=ax1.plot(x,y, color='r', label='Blue stars')
l2,=ax2.plot(x,y, color='g')
l3,=ax3.plot(x,y, color='b')
ax1.set_title('2012/09/15')
plt.legend([l1, l2, l3],["HHZ 1", "HHN", "HHE"])
plt.show()
Note that you pass to legend
not the axes, as in your example code, but the lines as returned by the plot
invocation.请注意,您传递给legend
不是轴,如示例代码中那样,而是plot
调用返回的线。
Of course you can invoke legend
after each subplot, but in my understanding you already knew that and were searching for a method for doing it at once.当然,您可以在每个子情节之后调用legend
,但据我所知,您已经知道这一点并且正在寻找一种方法来立即执行此操作。
This does what you want and overcomes some of the problems in other answers:这可以满足您的需求并克服其他答案中的一些问题:
import matplotlib.pyplot as plt
labels = ["HHZ 1", "HHN", "HHE"]
colors = ["r","g","b"]
f,axs = plt.subplots(3, sharex=True, sharey=True)
# ---- loop over axes ----
for i,ax in enumerate(axs):
axs[i].plot([0,1],[1,0],color=colors[i],label=labels[i])
axs[i].legend(loc="upper right")
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.