我使用matplotlib绘制相同类型的信息,但是针对不同的国家,有多个子图。也就是说,我在一个3x3的网格上有9个图,所有的线都是相同的(当然,每条线的值不同)。
然而,我还没有想出如何在图上只放一个图例(因为所有9个子图都有相同的线条)。
我该怎么做?
发布于 2017-10-25 07:36:18
还有一个很好的函数get_legend_handles_labels()
,你可以在最后一个轴上调用(如果你迭代它们的话),它将从label=
参数中收集所需的一切:
handles, labels = ax.get_legend_handles_labels()
fig.legend(handles, labels, loc='upper center')
发布于 2012-03-23 18:50:50
figlegend可能就是你要找的:http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figlegend
示例如下:http://matplotlib.org/examples/pylab_examples/figlegend_demo.html
另一个例子:
plt.figlegend( lines, labels, loc = 'lower center', ncol=5, labelspacing=0. )
或者:
fig.legend( lines, labels, loc = (0.5, 0), ncol=5 )
发布于 2013-06-27 02:54:50
对于具有多个轴的figure
中单个图例的自动定位,就像使用subplots()
获得的一样,以下解决方案非常有效:
plt.legend( lines, labels, loc = 'lower center', bbox_to_anchor = (0,-0.1,1,1),
bbox_transform = plt.gcf().transFigure )
使用bbox_to_anchor
和bbox_transform=plt.gcf().transFigure
,您可以定义一个figure
大小的新边界框作为loc
的引用。使用(0,-0.1,1,1)
将此边界框稍微向下移动,以防止图例被放置在其他艺术家的上方。
fig.tight_layout()
:在使用OBS之后和使用OBS之前使用此解决方案
https://stackoverflow.com/questions/9834452
复制相似问题