简体   繁体   中英

Matplotlib global legend for lots of subplots

i have some problem figuring out how to force matplotlib to add a legend where i want.

The figures i currently have look like this: 在此处输入图片说明

在此处输入图片说明

I generate this 2 paged plot with the following script:

n = 1
trn = True
for i in diff.keys():
    plt.subplot(8, 4, n)
    plt.xlim([0, rounds + 1])
    plt.locator_params(axis='y', nbins=5)
    if PEPTIDE_KD[i] == 1e-2:
        plt.plot(x_cord, [x[0] for x in diff[i]], 'ro--', label='asd')
        plt.plot(x_cord, [x[1] for x in diff[i]], 'rv--', label='bsd')
    else:
        plt.plot(x_cord, [x[0] for x in diff[i]], 'bo--', label='asd')
        plt.plot(x_cord, [x[1] for x in diff[i]], 'bv--', label='csd')
    plt.title(i)
    n += 1
    if n == 33 and trn:
        n = 1
        trn = False
        plt.suptitle('Ligand energies')
        plt.locator_params(axis='y', nbins=5)
        plt.subplots_adjust(hspace=0.35)
        plt.show()

plt.legend(bbox_to_anchor=(-0.05, 1), loc=1)
plt.locator_params(axis='y', nbins=5)
plt.subplots_adjust(hspace=0.35)
plt.show()

However i would like to place the legend at the left side of the very first subplot, or to the right side of last subplot in the first line.

I can do this with an if line == 0 bla bla, but the problem is as you can see in the plots i attached that for example the last plot only contains blue data, hence only the blue legend will show. I would like to place a full legend (red and blue) as well to the very same place. I dont even know where blue and red plot will be placed beforehand.

Is this possible?

尝试使用图形图例 ,该图例将为您图形中绘制的任何线条创建一个图例,并将其相对于图形放置

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM