from matplotlib.pyplot import *
ficheiros = ['120318.nc', '120319.nc', '120320.nc', '120321.nc']
fig = figure()
fig.suptitle('concentration profile analysis')
for a in range(len(ficheiros)):
# dados is here defined
level = dados.variables['level'][:]
ax = fig.add_subplot(2,2,a+1)
xticks(range(8), ['0h','3h','6h','9h','12h','15h','18h','21h'])
ax.set_xlabel('time (hours)')
ax.set_ylabel('CONC ($\mu g. m^{-3}$)')
for index in range(len(level)):
conc = dados.variables['CONC'][4:12,index] * 1e9
ax.plot(conc,label=str(level[index])+'m')
dados.close()
ax.legend(bbox_to_anchor=(1.05, 0), loc='lower left', borderaxespad=0.)
# it will place the legend on the outer right-hand side of the last axes
show()
6 回答
figlegend可能是您要找的内容:http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figlegend
示例:http://matplotlib.org/examples/pylab_examples/figlegend_demo.html
另一个例子:
要么:
还有一个很好的函数
get_legend_handles_labels()
你可以调用最后一个轴(如果你迭代它们),它们将从label=
参数收集你需要的一切:你只需要在循环之外询问一次传奇 .
例如,在这种情况下,我有4个子图,具有相同的线和一个图例 .
对于具有多个轴的
figure
中的单个图例的自动定位,如使用subplots()
获得的那些,以下解决方案非常有效:使用
bbox_to_anchor
和bbox_transform=plt.gcf().transFigure
,您将定义figure
大小的新边界框作为loc
的引用 . 使用(0,-0.1,1,1)
将此装饰框略微向下移动,以防止图例被放置在其他艺术家之上 .OBS:在使用
fig.set_size_inches()
之后使用此解决方案并在使用fig.tight_layout()
之前虽然比较晚了,但是我的假轴'然后关闭,所以只有传说显示 . 结果:https://i.stack.imgur.com/5LUWM.png .
这个答案是对@Evert's传奇位置的补充 .
由于图例和子图 Headers 的重叠,我对@Evert的解决方案的第一次尝试失败了 .
事实上,重叠是由
fig.tight_layout()
引起的,它改变了子图的布局而没有考虑图形图例 . 但是,fig.tight_layout()
是必要的 .为了避免重叠,我们可以通过
fig.tight_layout(rect=(0,0,1,0.9))
告诉fig.tight_layout()
为图形的图例留出空格 .Description of tight_layout() parameters .