简体   繁体   中英

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM