Python:Matplotlib子图的组合图例

时间:2017-09-18 15:01:53

标签: python matplotlib legend subplot

我试图在Jupiter Notebook中制作组合图例。当我从例子中尝试各种代码时,我得到一个空的传说。这些示例工作得很好,但是当我将它实现到我自己的代码中时会出现问题。有任何想法吗? 结果:
Result of presented code 代码:

fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, figsize=(15,10))
l1 = ax1.plot(time[18206:18226],tpm2[18206:18226], 'r', label='Chilbolton 2')
ax1.set_title('Difference in Hydrometeor Count Per Minute Over Time')
ax1.set_ylim([0,14000])
ax1.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)

l2 = ax2.plot(time[18206:18226],tpm1[18206:18226], 'b', label='Chilbolton 2')
ax2.set_ylim([0,14000])
ax2.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)

l3 = ax3.plot(time[18206:18226],diff[18206:18226], 'k', label='D.P.M.')
ax3.plot(time[18206:18226],np.zeros(20),'k--')
ax3.set_xlabel('Time (10th February to 29th April)')
ax3.set_ylim([-3000,3000])
ax3.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)

#plt.legend( handles=[l1, l2, l3], labels=['l1','l2','l3'],loc="upper left", bbox_to_anchor=[0, 1],
#           ncol=2, shadow=True, title="Legend", fancybox=True)
fig.legend((l1, l2, l3), ('Line 1', 'Line 2', 'Line 3'), 'upper left')
# ('Chilbolton 2','Chilbolton 2','D.P.M.'), loc = (0.5, 0), ncol=1 )

plt.ylabel('Hydrometeor Count (#)')
# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plot.
#f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[-1:]], rotation=90, visible=True)
plt.show()

2 个答案:

答案 0 :(得分:1)

即使您只绘制一行,

ax.plot()也会返回列表的线条艺术家。因此,当您编写l1 = ax1.plot(...)时,会将长度为1的列表分配给l1。同上l2l3。这会导致fig.legend()出现问题,只需要线艺术家对象。

您可以通过多种方式解决此问题。最常用的方法是语法:

l1, = ax1.plot(...

插入逗号会将返回列表的唯一元素指定给l1。你也可以做l1 = ax1.plot(...)[0]。或者,在您的情况下,您可以将您的图例调用修改为fig.legend((l1[0],l2[0],l3[0]),...)

所以,

import maptlotlib.pyplot as plt

fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, figsize=(15,10))

l1, = ax1.plot([0,1],[0,14000])
ax1.set_title('Difference in Hydrometeor Count Per Minute Over Time')
ax1.set_ylim([0,14000])
ax1.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)

l2, = ax2.plot([0,1],[0,14000])
ax2.set_ylim([0,14000])
ax2.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)

l3, = ax3.plot([0,1],[-3000,3000])
ax3.plot(time[18206:18226],np.zeros(20),'k--')
ax3.set_xlabel('Time (10th February to 29th April)')
ax3.set_ylim([-3000,3000])
ax3.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)

fig.legend((l1, l2, l3), ('Line 1', 'Line 2', 'Line 3'), 'upper left')

enter image description here

答案 1 :(得分:0)

作为解决方法,您可以使用Patch

创建自己的自定义图例
import numpy as np            
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import random

tx = range(20)
t1 = np.random.randint(0, 14000, 20)
t2 = np.random.randint(0, 14000, 20)
t3 = np.random.randint(-3000, 3000, 20)

labels = ['Chilbolton 2', 'Chilbolton 2', 'D.P.M.']

fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, figsize=(15,10))
l1 = ax1.plot(tx, t1, 'r', label=labels[0])
ax1.set_title('Difference in Hydrometeor Count Per Minute Over Time')
ax1.set_ylim([0,14000])
ax1.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)

l2 = ax2.plot(tx,t2, 'b', label=labels[1])
ax2.set_ylim([0,14000])
ax2.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)

l3 = ax3.plot(tx,t3, 'k', label=labels[2])
ax3.plot(tx,np.zeros(20),'k--')
ax3.set_xlabel('Time (10th February to 29th April)')
ax3.set_ylim([-3000,3000])
ax3.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)

# Create custom legend
leg1 = mpatches.Patch(color='r')
leg2 = mpatches.Patch(color='b')
leg3 = mpatches.Patch(color='k')
fig.legend(handles=[leg1, leg2, leg3], labels=labels, loc="upper left")

plt.ylabel('Hydrometeor Count (#)')
# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plot.
#f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in fig.axes[-1:]], rotation=90, visible=True)
plt.show()

给你:

Demo legend