Matplotlib:为不同的数字指定图例

时间:2018-04-25 08:37:06

标签: matplotlib legend

在循环中我正在计算一些东西然后我想用两个不同的数字绘制它们。我把数字设置为

susc_comp, (ax1,ax2) = plt.subplots( 2, 1, sharex=True, sharey='none', figsize=(8.3,11.7)) 
cole_cole, (ax3) = plt.subplots( 1, 1, sharex='none', sharey='none', figsize=(8.3,11.7))
for j,temp in enumerate(indexes_T[i]):

     Calculate and plot in the corresponding ax1,ax2,ax3

plt.legend(loc=0, fontsize='small', numpoints = 1, ncol=(len(indexes_T[i]))/2, frameon=False)
susc_comp.savefig('suscp_components'+str(field)+'Oe.png', dpi=300)
cole_cole.savefig('Cole_Cole'+str(field)+'Oe.png', dpi=300)

但是我只在sus_comp图中得到了传说(这两个数字都是相同的传说)。如何选择图形并为每个图形添加图例?

非常感谢!

1 个答案:

答案 0 :(得分:1)

您可以直接致电figure.legend(虽然我认为这可能比plt.legend的功能少)。因此,我会以不同的方式做到这一点。

这个问题表明两个传说都是一样的。另外,第二个图中只有1个轴。因此,一种解决方案是从ax3获取句柄和标签,然后手动将这些应用于两个数字。简化示例如下:

import matplotlib.pyplot as plt

susc_comp, (ax1, ax2) = plt.subplots(1,2)
cole_cole, ax3 = plt.subplots()

ax1.plot([1,2,3], label="Test1")
ax2.plot([3,2,1], label="Test2")

ax3.plot([1,2,3], label="Test1")
ax3.plot([3,2,1], label="Test2")

handles, labels = ax3.get_legend_handles_labels()

ax2.legend(handles, labels, loc=1, fontsize='small', numpoints = 1)
ax3.legend(handles, labels, loc=1, fontsize='small', numpoints = 1)

plt.show()

这给出了以下2个数字:

enter image description here

enter image description here