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?
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With