Home > Software engineering >  How to include the outside legend into the generated file?
How to include the outside legend into the generated file?

Time:08-12

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?

CodePudding user response:

One option is to tell tight_layout() not to use the full width. That leaves enough room for your legend. I'm not sure if there's a way measure the width of your legend in code, but I experimentally found this fits your legend:

import matplotlib.pyplot as plt
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(rect=(0, 0, 0.84, 1))
axes[0].legend(loc="upper left", bbox_to_anchor=(1,0,1,1))

plt.show()

CodePudding user response:

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))

plt.subplots_adjust(right=0.80)
fig.savefig("test.png")

Saved image:

enter image description here

  • Related