在matplotlib的gridspec模块中在一个轴上放置2个不同的图例

Ben*_*son 2 plot matplotlib

我现在正在使用matplotlib的gridspec模块进行绘图.我想在特定的轴上添加2个不同的图例,比如matplotlib中提到的图例:同一图表上的2个不同的图例.

然而,有了gridspec,我总是会在另一个轴上放置一个传奇而丢失一个.

这是我的代码:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure()
gs1 = gridspec.GridSpec(8, 4)
gs1.update(left=0.1, right=0.65, bottom=0.06, top=1, hspace=0)

axF = plt.subplot(gs1[0, :])
axE = plt.subplot(gs1[1, :],sharex=axF)
axPA = plt.subplot(gs1[2, :],sharex=axF)
axMiu = plt.subplot(gs1[3:7, :],sharex=axF)
axRes = plt.subplot(gs1[7, :],sharex=axF)

hd1=axMiu.errorbar(range(5),map(lambda x:x+1,range(5)), fmt='o',     color='black', mfc='none',markersize=5, label='hehe')
hd2=axMiu.errorbar(range(5),map(lambda x:x+2,range(5)), fmt='-',         color='fuchsia',markersize=5, linewidth=2, label='heihei')

first_legend=plt.legend(prop={'size':12},labelspacing=0,handles=[hd2],loc='upper right')
axMiu.add_artist(first_legend)
plt.legend(prop={'size':12},labelspacing=0,handles=[hd1],loc='right')
plt.show()
Run Code Online (Sandbox Code Playgroud)

tmd*_*son 5

你需要使用axis.legend,而不是plt.legend.

例如,制作最后4行:

first_legend=axMiu.legend(prop={'size':12},labelspacing=0,handles=[hd2],loc='upper right')
axMiu.add_artist(first_legend)
axMiu.legend(prop={'size':12},labelspacing=0,handles=[hd1],loc='right')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述