idealistikz
idealistikz

Reputation: 1267

Dynamically place legend in plot

I am creating plots in pyplot in Python. Each plot contains two or more subplots. I know I can statically place a legend in the plot by defining the parameter loc; however, my choice of location will sometimes cover the data in my plot. How would I place the legend dynamically in the location that interferes with the data the least?

Upvotes: 1

Views: 1038

Answers (1)

unutbu
unutbu

Reputation: 880717

As tcaswell has already stated, use ax.legend(loc='best'):

import matplotlib.pyplot as plt
import numpy as np
pi = np.pi
sin = np.sin
t = np.linspace(0.0, 2 * pi, 50)
markers = ['+', '*', ',', ] + [r'$\lambda$']
phases = [0, 0.5]
fig, ax = plt.subplots(len(phases))
for axnum, phase in enumerate(phases):
    for i, marker in enumerate(markers, 1):
        ax[axnum].plot(t, i*sin(2*t + phase*pi), marker=marker,
                   label='$i,\phi = {i},{p}$'.format(i=i, p=phase))
    ax[axnum].legend(loc='best', numpoints=1)
plt.show()

enter image description here

Interestingly, the location of the legend is not fixed. If you move the graph using the GUI, the location of the legend will readjust itself automatically.

Upvotes: 2

Related Questions