user308827
user308827

Reputation: 22021

Creating matplotlib legend with dynamic number of columns

I would like to create a legend in matplotlib with at max 5 entries per column. Right now, I can manually set the number of columns like so:

leg = plt.legend(loc='best', fancybox=None, ncol=2)

How do I modify this so that at most 5 entries are allowed per column?

Upvotes: 5

Views: 4447

Answers (1)

Joe Kington
Joe Kington

Reputation: 284830

There's no built-in way to specify a number of rows instead of a number of columns. However, you can get the number of items that would be added to the legend using the ax._get_legend_handles() method.

For example:

import numpy as np
import matplotlib.pyplot as plt

numlines = np.random.randint(1, 15)
x = np.linspace(0, 1, 10)

fig, ax = plt.subplots()
for i in range(1, numlines + 1):
    ax.plot(x, i * x, label='$y={}x$'.format(i))

numitems = len(list(ax._get_legend_handles()))
nrows = 5
ncols = int(np.ceil(numitems / float(nrows)))

ax.legend(ncol=ncols, loc='best')

plt.show()

enter image description here

Upvotes: 9

Related Questions