Skip to content
Advertisement

Adjusting global legend (labels) of a plot with subplots (which currently overlaps with the plot) – matplotlib, python

I am trying to add a global legend to a plot, the code below does that but the legend then overlaps with the given plot (I’ll add the plot below). Is there a way to adjust the legends? The other StackOverflow answers are focused on a single plot and are not working with subplots (or maybe I am doing something wrong).

Edit: Right now both the graphs are overlapping and hence the red one isn’t visible.

fig, axes = plt.subplots(n, m, figsize=(15, 8))
for var, ax in zip(vars_to_plot, axes.flat):
    for solution in solutions:
        ax.plot(
            solution.summary_variables["Cycle number"],
            solution.summary_variables[var],
        )
    ax.set_xlabel("Cycle number")
    ax.set_ylabel(var)
    ax.set_xlim([1, solution.summary_variables["Cycle number"][-1]])

fig.tight_layout()
fig.legend(['this is plot 1', 'this is plot 2'], loc='lower right')
plt.savefig("plot.png", dpi=300)

The plot

Advertisement

Answer

Suggest you put the legend outside the figure:

fig.legend(['this is plot 1', 'this is plot 2'], loc='lower left', 
           bbox_to_anchor=(1.0, 0.05))

and then save the figure with plt.savefig("plot.png", bbox_inches='tight') to allow the figure to expand to encompass the legend.

There are other things you can do, but I think this is the simplest…

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement