Control the number of rows within a legend

2019-04-05 21:52发布

问题:

I am currently trying to plot a large amount of data on a single plot. I have structured my representation using repeated colors and symbols. However, when plotting the final results, the legend appears slightly off because I cannot control the number of rows within it. Thus, instead of getting 5 repeated green, then 5 repeated red, 5 repeated blue then 2 other, I get 5 -4 -4 -4 (where I would have prefered 5 - 5 - 5 - 2)

You can clearly see this in attached image.

Right now I use these options for the legend:

axp.legend(loc="lower right",ncol=4)

回答1:

I also had this problem a couple of times and use this workaround by adding dummy items to the legend to fill the last column, if there are more elegant methods available I would also be very interested to hear about them.

import numpy as np
import matplotlib.pylab as pl

pl.figure()

pl.plot(np.arange(10), np.random.random([10,5]), color='r', label='red')
pl.plot(np.arange(10), np.random.random([10,5]), color='g', label='green')
pl.plot(np.arange(10), np.random.random([10,5]), color='b', label='blue')
pl.plot(np.arange(10), np.random.random([10,2]), color='k', label='black')

# Add empty dummy legend items
pl.plot(np.zeros(1), np.zeros([1,3]), color='w', alpha=0, label=' ')

pl.legend(ncol=4)