Skip to content

[ENH]: matplotlib legend fill columnswise #27067

Open
@pepijnvtol

Description

@pepijnvtol

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:

def flip(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
    """
    return itertools.chain(*[items[i::ncol] for i in range(ncol)])

handles, labels = axs.get_legend_handles_labels()
ncol = 2
ax.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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions