Reputation: 10153
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
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
(I've used plt.style.use('ggplot') in the plot above.)
See also the matplotlib legend guide.
Upvotes: 14
Reputation: 28936
DataFrame.plot
takes a legend
argument, which can be True/False/'reverse'. You want legend='reverse'
Upvotes: 21