简体   繁体   中英

Change order of columns in stacked bar plot

I'm using the following code to produce a stacked bar plot from a pandas data frame in Python ( data is the DataFrame object).

data.plot(kind='bar', stacked=True, figsize=(15, 10), x='Species', fontsize=16,
          rot=0)

Here is an IPython Notebook for context.

I would like to change the order of the columns. The seaborn.barplot function has the x_order argument, which does exactly what I would like. However, it does not support stacked bar plots directly like the pandas.DataFrame.plot function does. What is the simplest way to reorder the columns?

You can manually rearrange the rows by permuting the numeric indices, like the answer given by @iayork, or alternatively you can set the index of your dataframe to be the column Species .

species = ['A', 'B', 'H', 'S', 'P', 'N']

data2 = data.set_index(['Species'])
data2.reindex(species).plot(kind='bar', stacked=True, figsize=(15, 10),
                            fontsize=16, rot=0)

By setting the index of data as Species , you can now permute the rows by their string labels, instead of numeric indices.

The simplest way is probably to rearrange your index.

data2 = data.loc[[5, 4, 3, 2, 1, 0]]

reverses the order in dataframe and plot.

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