如何在matplotlib子块下添加图例?

2024-05-28 11:17:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一个3列的子块图下面添加一个图例。

我试过以下方法:

fig, ax = plt.subplots(ncols=3)
ax[0].plot(data1)
ax[1].plot(data2)
ax[2].plot(data3)

ax_sub = plt.subplot(111)
box = ax_sub.get_position()
ax_sub.set_position([box.x0, box.y0 + box.height * 0.1,box.width, box.height * 0.9])
ax_sub.legend(['A', 'B', 'C'],loc='upper center', bbox_to_anchor=(0.5, -0.3),fancybox=False, shadow=False, ncol=3)
plt.show()

但是,这只会创建一个空帧。当我注释掉ax_子部分时,我的子块显示得很好(但没有图例…)。。。

非常感谢!

这与How to put the legend out of the plot密切相关


Tags: theto方法boxfalseplotfigposition
1条回答
网友
1楼 · 发布于 2024-05-28 11:17:23

传说需要知道它应该显示什么。默认情况下,它将从创建时所在的轴中获取标记的艺术家。因为这里的轴ax_sub是空的,所以图例也将是空的。

无论如何,使用ax_sub可能没有太多意义。我们可以使用中轴(ax[1])来放置图例。然而,我们仍然需要所有应该出现在传说中的艺术家。对于行,这很简单;可以提供一个行列表作为handles参数的句柄。

import matplotlib.pyplot as plt
import numpy as np

data1,data2,data3 = np.random.randn(3,12)

fig, ax = plt.subplots(ncols=3)
l1, = ax[0].plot(data1)
l2, = ax[1].plot(data2)
l3, = ax[2].plot(data3)

fig.subplots_adjust(bottom=0.3, wspace=0.33)

ax[1].legend(handles = [l1,l2,l3] , labels=['A', 'B', 'C'],loc='upper center', 
             bbox_to_anchor=(0.5, -0.2),fancybox=False, shadow=False, ncol=3)
plt.show()

enter image description here

相关问题 更多 >