Reverse the order of a legend

Question:

I use the following code to plot the bar graph and need to present a legend in reverse order. How can I do it?

colorsArr = plt.cm.BuPu(np.linspace(0, 0.5, len(C2)))
p = numpy.empty(len(C2), dtype=object)
plt.figure(figsize=(11, 11))

prevBar = 0
for index in range(len(C2)):
    plt.bar(ind, C2[index], width, bottom=prevBar, color=colorsArr[index],
            label=C0[index])
    prevBar = prevBar + C2[index]

# Positions of the x-axis ticks (center of the bars as bar labels)
tick_pos = [i + (width/2) for i in ind]

plt.ylabel('Home Category')
plt.title('Affinity - Retail Details(Home category)')

# Set the x ticks with names
plt.xticks(tick_pos, C1)
plt.yticks(np.arange(0, 70000, 3000))
plt.legend(title="Line", loc='upper left')

# Set a buffer around the edge
plt.xlim(-width*2, width*2)
plt.show()
Asked By: YAKOVM

||

Answers:

I’ve not tested this as I don’t have your data, but this is based on the documentation here on controlling legend entries.

handles = []
for index in range(len(C2)):
    h = plt.bar(ind, C2[index], width, bottom=prevBar, color=colorsArr[index], label=C0[index])
    handles.append(h)
    prevBar = prevBar + C2[index]

plt.legend(title="Line", loc='upper left', handles=handles[::-1])
Answered By: Jamie Bull

You could call

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[::-1], labels[::-1], title='Line', loc='upper left')

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(2016)

C0 = list('ABCDEF')
C2 = np.random.randint(20000, size=(len(C0), 3))
width = 1.0
C1 = ['foo', 'bar', 'baz']
ind = np.linspace(-width, width, len(C1))


colorsArr = plt.cm.BuPu(np.linspace(0, 0.5, len(C2)))
fig = plt.figure(figsize=(11,11))
ax = fig.add_subplot(1, 1, 1)

prevBar = 0
for height, color, label in zip(C2, colorsArr, C0):
    h = ax.bar(ind, height, width, bottom=prevBar, color=color, label=label)
    prevBar = prevBar + height

plt.ylabel('Home Category')
plt.title('Affinity - Retail Details(Home category)')

# positions of the x-axis ticks (center of the bars as bar labels)
tick_pos = [i+(width/2.0) for i in ind]
# set the x ticks with names
plt.xticks(tick_pos, C1)
plt.yticks(np.arange(0,70000,3000))

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[::-1], labels[::-1], title='Line', loc='upper left')

plt.show()

enter image description here

Answered By: unutbu

Use a negative number for the legend vertical spacing, like this:

matplotlib.pyplot.stackplot(X, *revDataValues,
    linewidth=1.0,
    edgecolor='black')

matplotlib.pyplot.legend(revNames,
    loc=6, bbox_to_anchor=(1.05, 0.5),
    labelspacing=-2.5, frameon=False,         # reverse legend
    fontsize=9.0)

Stacked Area Chart with reversed legend

Answered By: Carl Drews

Or you could use the simpler

handles, labels = ax.get_legend_handles_labels()
ax.legend(reversed(handles), reversed(labels), title='Line', loc='upper left')
Answered By: Vaiaro

The newest version of matplotlib (>=3.7) now provides this feature out of the box:

plt.legend(title="Line", loc='upper left', reverse=True)

The default is reverse=False (the previous behaviour)—setting it to reverse=True will now show the entries in the legend in the same order as the stacked bars. See Axes.legend documentation.

Answered By: Timmm
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.