Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork7.9k
Open
Labels
Description
Problem
I would like to have the options to determine how the legend should be filled, i.e. rowwise or columnwise. At the moment the rows are filled first. For example:
x = np.arange(0, 10)fig, ax = plt.subplots()ax.plot(x, x, label='1')ax.plot(x, x+1, label='2')ax.plot(x, x+ 2, label='3')ax.plot(x, x+3, label='4')ax.legend(ncols=2)plt.show()
The legend looks like:
1 | 3 |
---|---|
2 | 4 |
What I would like is:
1 | 2 |
---|---|
3 | 4 |
Proposed solution
Not my own solution, but found here:https://stackoverflow.com/questions/10101141/matplotlib-legend-add-items-across-columns-instead-of-down
One way to implement this is to add a keyword and use this function:
defflip(items,ncol):""" Flips the order of items in a list by grouping them into columns. *used to fill columns of legends first* Parameters: items (list): The list of items to be flipped. ncol (int): The number of columns to group the items into. Returns: itertools.chain: A chain object containing the flipped items. Source: https://stackoverflow.com/questions/10101141/ matplotlib-legend-add-items-across-columns-instead-of-down """returnitertools.chain(*[items[i::ncol]foriinrange(ncol)])handles,labels=axs.get_legend_handles_labels()ncol=2ax.legend(flip(handles,ncol),flip(labels,ncol),ncol=ncol)
At the moment it is a seperate function, but based on an extra keyword-argument one could check if the labels should be distributed column or row wise and use the ncol argument to change this.