YAKOVM
YAKOVM

Reputation: 10153

Reverse legend order pandas plot

I have following code to show stacked bar

handles = df.toPandas().set_index('x').T.plot(kind='bar', stacked=True, figsize=(11,11))
    plt.legend(loc='best', title="Line", fontsize = 'small', framealpha=0)
    plt.ylabel("'" + lineName + "'")
    plt.show()

I want to reverse the order of legend I used handles=handles[::-1]but I got an error.

Upvotes: 10

Views: 10285

Answers (2)

Avi
Avi

Reputation: 454

Here's a minimal example using matplotlib directly for the legend.

df = pd.DataFrame({'a': np.random.randn(10) + 1, 'b': np.random.randn(10),
                   'c': np.random.randn(10) - 1}, columns=['a', 'b', 'c'])
ax = df.plot(kind='bar', stacked=True)
handles, labels = ax.get_legend_handles_labels()
ax.legend(reversed(handles), reversed(labels), loc='upper left')  # reverse both handles and labels

bar chart

(I've used plt.style.use('ggplot') in the plot above.)

See also the matplotlib legend guide.

Upvotes: 14

TomAugspurger
TomAugspurger

Reputation: 28936

DataFrame.plot takes a legend argument, which can be True/False/'reverse'. You want legend='reverse'

Upvotes: 21

Related Questions