繁体   English   中英

如何在matplotlib中的子图下面添加图例?

[英]How to add legend below subplots in matplotlib?

我试图在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_sub部分时,我的子图显示很好(但没有图例...)...

非常感谢!

这与如何将图例排除在情节中密切相关

图例需要知道应该显示什么。 默认情况下,它将从创建艺术家的轴中获取带标签的艺术家。由于此处的轴ax_sub为空,因此图例也将为空。

无论如何,使用ax_sub可能没有太大意义。 我们可以改用中轴( ax[1] )放置图例。 但是,我们仍然需要所有出现在图例中的艺术家。 对于行,这很容易; 可以提供一行列表作为handles参数的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()

在此处输入图片说明

暂无
暂无

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

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