Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining fig.legend with subfigures in matplotlib

EDIT: This has been fixed in last versions of matplotlib here


Disclaimer: I am aware that using subfigures is irrelevant in this simple example, the latter is used only to show my problem: I want to be able to use fig.legend() with fig.subfigures1.


I am currently discovering the new subfigure module of matplotlib. I noticed that figure legends created using fig.legend() does not show up when the main figure contains subfigures:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1, 10, 10)
y1 = x
y2 = -x

fig = plt.figure(constrained_layout=True)
subfigs = fig.subfigures(nrows=2, ncols=1)

for subfig in subfigs:
    axarr = subfig.subplots(1, 2)
    for ax in axarr.flatten():
        l1, = ax.plot(x, y1, label='line1')
        l2, = ax.plot(x, y2, label='line2')
            #
        ax.legend()
    # subfig.legend(handles=[l1, l2], loc='upper center', ncol=2)
fig.legend(handles=[l1, l2], loc='upper center', ncol=2)
plt.savefig('subfigures_figlegend.png', dpi=200)

enter image description here

Note how that figure legend is absent. For comparison, note that is shows up when using only plt.subplots:

fig, axarr = plt.subplots(2, 2, constrained_layout=True)
for ax in axarr.flatten():
    l1, = ax.plot(x, y1, label='line1')
    l2, = ax.plot(x, y2, label='line2')
    #
    ax.legend()
fig.legend(handles=[l1, l2], loc='upper center', ncol=2)
plt.savefig('subplots_figlegend.png', dpi=200)

enter image description here

like image 488
Liris Avatar asked Apr 08 '26 02:04

Liris


1 Answers

When I ran your code the legend was there, but it was behind and slightly above the plot, and then cut off when plt.savefig() is called. I was able to get it to work with the bbox_inches='tight' argument of plt.savefig() and the following to move the legend.

fig.legend(handles=[l1, l2], bbox_to_anchor=(0.7, 1.1), ncol=2)

enter image description here

like image 186
cazman Avatar answered Apr 10 '26 15:04

cazman