Display legend in reverse order

Original report at SourceForge, opened Mon Jul 16 12:03:19 2007

It would be nice if the legend() command had an option
to print the legend in reverse order. This would be useful when many lines are drawn on a plot and you would like the first legend element to correspond to the top-most curve of the plot. This is good form, especially when the the same color is used multiple times. The curves could be plotted in reverse order, but this is not always convenient.

For example, if I had the loop:

for index,number in enumerate(arange(16)*2):
plot(y_data[index,:],label=’Number %%i’%%number)
legend()

I would have to rewrite this as:
for index,number in enumerate(arange(15,-1,-1)*2):
plot(y_data[(15-index),:],label=’Number %%i’%%number)
legend()

It would be more convenient if I could use the original
plot loop and just use a command like:
legend(reversed=True)

Author: Fantashit

2 thoughts on “Display legend in reverse order

  1. In the current implementation, the legend would be displayed in an order of their creation within a same artist class. But if there are multiple classes of artist (e.g., patches and lines), the order is : lines, patches, collections and containers which is rather arbitrary in my view.
    Given that these situations, I think it is best to let a user explicitly specify the order of legend items. And I’m not very inclined to implement an option like reverse.

    For those who do not want to track the artists they are creating, here’s a workaround.

    http://matplotlib.sourceforge.net/users/legend_guide.html#adjusting-the-order-of-legend-items

    And I’m closing this issue.

  2. General approach to fix the problem:

    handles, labels = axis.get_legend_handles_labels()
    axis.legend(reversed(handles), reversed(labels), loc='upper left')  # reverse to keep order consistent
    

Comments are closed.