Matplotlib在子图中传说

Cat*_*aCM 25 python matplotlib

我想把传说放在下面的每个子图中.我试过用plt.legend但它没有用.

有什么建议?

提前致谢 :-)

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()
Run Code Online (Sandbox Code Playgroud)

结果情节 根据atomh33ls的建议:

ax1.legend("HHZ 1",loc="upper right")
ax2.legend("HHN",loc="upper right")
ax3.legend("HHE",loc="upper right")
Run Code Online (Sandbox Code Playgroud)

图例位置是固定的,但是字符串似乎有问题,因为每个字母都放在一个新行中.

有谁知道如何解决它?

在此输入图像描述

ato*_*3ls 39

这应该工作:

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")
Run Code Online (Sandbox Code Playgroud)

  • 是的,它将图例放置在正确的位置。谢谢!唯一的问题是,它将每个字母放在一行中。你知道如何避免这种情况吗? (2认同)

gbo*_*ffi 16

您想要的是什么,因为在当前轴中plt.legend()放置一个图例,在您的情况下放在最后一个中.

另一方面,如果您可以满足于在最后一个子图中放置一个综合图例,那么您可以这样做

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

请注意,您传递的legend不是轴,如示例代码中所示,而是传递给plot调用返回的行.

PS

当然你可以legend在每个子情节之后调用,但在我的理解中你已经知道并且正在寻找一种方法来实现它.


com*_*hys 8

这可以实现您想要的并克服其他答案中的一些问题:

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()
Run Code Online (Sandbox Code Playgroud)

...产生... 次要情节