Jessie
Jessie

Reputation: 105

Plot legend obscures plot lines in figure

I'm using this code found in matplotlib's gallery:

import numpy as np
import matplotlib.pyplot as plt


fig = plt.figure()
x = np.arange(10)
y = 2.5 * np.sin(x / 20 * np.pi)
yerr = np.linspace(0.05, 0.2, 10)

plt.errorbar(x, y + 3, yerr=yerr, label='both limits (default)')

plt.errorbar(x, y + 2, yerr=yerr, uplims=True, label='uplims=True')

plt.errorbar(x, y + 1, yerr=yerr, uplims=True, lolims=True,
             label='uplims=True, lolims=True')

upperlimits = [True, False] * 5
lowerlimits = [False, True] * 5
plt.errorbar(x, y, yerr=yerr, uplims=upperlimits, lolims=lowerlimits,
             label='subsets of uplims and lolims')

plt.legend(loc='lower right')

and, I receive the following output in the terminal in jupyter:

enter image description here

However, in the matplotlib gallery, the legend is tucked in nicely below the errorbar limit selection:

enter image description here

How would I sort this out? I'm having the same issue with a few other plots at the moment with my project, with the legent obstructing the plot, and I've made no progress so far.

Upvotes: 1

Views: 144

Answers (1)

Arav
Arav

Reputation: 111

For this example simply adding plt.tight_layout() in the end seems to fix the overlap.

import numpy as np
import matplotlib.pyplot as plt


fig = plt.figure()
x = np.arange(10)
y = 2.5 * np.sin(x / 20 * np.pi)
yerr = np.linspace(0.05, 0.2, 10)

plt.errorbar(x, y + 3, yerr=yerr, label='both limits (default)')

plt.errorbar(x, y + 2, yerr=yerr, uplims=True, label='uplims=True')

plt.errorbar(x, y + 1, yerr=yerr, uplims=True, lolims=True,
             label='uplims=True, lolims=True')

upperlimits = [True, False] * 5
lowerlimits = [False, True] * 5
plt.errorbar(x, y, yerr=yerr, uplims=upperlimits, lolims=lowerlimits,
             label='subsets of uplims and lolims')


plt.legend(loc='lower right')
plt.tight_layout() # <- add this

However, to maintain consistency you can adjust the size of the figure to avoid overlapping legends.

For this example it would be:

import numpy as np
import matplotlib.pyplot as plt


fig = plt.figure(figsize=(7,5)) # <- add a figsize
x = np.arange(10)
y = 2.5 * np.sin(x / 20 * np.pi)
yerr = np.linspace(0.05, 0.2, 10)

plt.errorbar(x, y + 3, yerr=yerr, label='both limits (default)')

plt.errorbar(x, y + 2, yerr=yerr, uplims=True, label='uplims=True')

plt.errorbar(x, y + 1, yerr=yerr, uplims=True, lolims=True,
             label='uplims=True, lolims=True')

upperlimits = [True, False] * 5
lowerlimits = [False, True] * 5
plt.errorbar(x, y, yerr=yerr, uplims=upperlimits, lolims=lowerlimits,
             label='subsets of uplims and lolims')


plt.legend(loc='lower right')

Upvotes: 2

Related Questions