9

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.

TomAugspurger
  • 28,234
  • 8
  • 86
  • 69
YAKOVM
  • 9,805
  • 31
  • 116
  • 217
  • Please include the error that occured, and some details about what this data frame is. – Jezzamon Feb 12 '16 at 23:19
  • For how to reverse the data frame, have a look here http://stackoverflow.com/questions/20444087/right-way-to-reverse-pandas-dataframe – Jezzamon Feb 12 '16 at 23:19

2 Answers2

19

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

TomAugspurger
  • 28,234
  • 8
  • 86
  • 69
  • It didn`t work :df.toPandas().set_index('Product_Line_Name').T.plot(kind='bar', stacked=True, figsize=(11,11), legend='reverse') plt.legend(loc='best', title="Line", fontsize = 'small', framealpha=0) plt.ylabel("'" + lineName + "'") plt.show() – YAKOVM Feb 13 '16 at 00:17
  • 1
    Your second legend overwrites the first one. – Stop harming Monica Feb 13 '16 at 00:37
  • 1
    @Goyo can I add second legend parameters to plot? or in legend say reverse it? – YAKOVM Feb 13 '16 at 00:46
14

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.

Avi
  • 454
  • 4
  • 7