Search code examples
pythonmatplotlibpnglegend

How to include the outside legend into the generated file?


I am plotting many lines on several axes, so I have a several fairly busy plots, thus I need to place the legend outside of the figure:

import numpy as np
nrows = 4
fig = plt.figure(figsize=(6, 2*nrows))
axes = fig.subplots(nrows=nrows, ncols=1)
names = [f"name-{n}" for n in range(10)]
for ax in axes:
    for n in names:
        ax.plot(np.arange(10),np.random.normal(size=10),label=n)
fig.tight_layout()
axes[0].legend(loc="upper left", bbox_to_anchor=(1,0,1,1))

which produces something like

sample chart

However, when I save the figure using fig.savefig("test.png"), I get this:

enter image description here

note the missing legend.

How do I save the figure so that the legend is included?


Solution

  • Use plt.subplots_adjust and you can customize the space around the figure. Here I just used plt.subplots_adjust(right=0.8) but you can adjust all the settings (including top, bottom, left, hspace, wspace)

    import numpy as np
    nrows = 4
    fig = plt.figure(figsize=(6, 2*nrows))
    axes = fig.subplots(nrows=nrows, ncols=1)
    names = [f"name-{n}" for n in range(10)]
    for ax in axes:
        for n in names:
            ax.plot(np.arange(10),np.random.normal(size=10),label=n)
    fig.tight_layout()
    axes[0].legend(loc="upper left", bbox_to_anchor=(1,0,1,1))
    
    fig.subplots_adjust(right=0.80)
    fig.savefig("test.png")
    

    Saved image:

    enter image description here