Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 224
user308827 Avatar asked Jan 11 '16 18:01

user308827


People also ask

How do I create a multi legend in MatPlotLib?

MatPlotLib with PythonPlace the first legend at the upper-right location. Add artist, i.e., first legend on the current axis. Place the second legend on the current axis at the lower-right location. To display the figure, use show() method.

How do I change the legend box size in MatPlotLib?

To place a legend on the figure and to adjust the size of legend box, use borderpad=2 in legend() method. To display the figure, use show() method.


1 Answers

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

like image 117
Joe Kington Avatar answered Oct 05 '22 06:10

Joe Kington