subplot matplotlib的常见图例

时间:2016-11-29 16:59:59

标签: python matplotlib plot

我正在使用matplotlib创建一个情节,似乎我遇到了一个问题。 我绘制了3个子图,我希望得到所有这些的共同传说

fig, (ax, ax2, ax3) = plt.subplots(3, 1, sharex=True)
ax.plot(FRAME1['T1'],FRAME1['Num'], marker = 'o', label='1')
ax2.plot(FRAME3['T1'],FRAME3['Num'], marker = 'o', label='2',color='r')
ax2.plot(FRAME4['T1'],FRAME4['Num'], marker = 'o', label='3',color='turquoise')
ax3.plot(FRAME2['T1'],FRAME2['Num'], marker = 'o', label='4',color='g')

ax.set_ylim(-118, -116.5)  
ax3.set_ylim(-136, -135)

plt.legend( (ax,ax2,ax3),loc="upper left", bbox_to_anchor=[0, 1],
           ncol=2, shadow=True, title="Legend", fancybox=True)

我使用了图例实例,但它仅在最后一个子图上显示legen。

1 个答案:

答案 0 :(得分:3)

当然,您需要在其中一个子图上显示图例。您决定选择哪一个。

为了显示图例中的所有四行,您需要提供对图例的线条的引用

plt.legend(handles = [line1, line2, ...])

另见Matplotlib legend guide 所以这是一个有效的例子

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randint(0,12,size=(12,4))
y = np.random.randint(0,8,size=(12,4))

fig, (ax, ax2, ax3) = plt.subplots(3, 1, sharex=True, figsize=(5,5))

l, = ax.plot(x[:,0],y[:,0], marker = 'o', label='1')
l2, =ax2.plot(x[:,1],y[:,1], marker = 'o', label='2',color='r')
l3, =ax2.plot(x[:,2],y[:,2], marker = 'o', label='3',color='turquoise')
l4, =ax3.plot(x[:,3],y[:,3], marker = 'o', label='4',color='g')


plt.legend( handles=[l, l2, l3, l4],loc="upper left", bbox_to_anchor=[0, 1],
           ncol=2, shadow=True, title="Legend", fancybox=True)

plt.show()

enter image description here