Reputation: 8304
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?
Upvotes: 1
Views: 5679
Reputation: 6699
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.
Upvotes: 1
Reputation: 2936
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.
Upvotes: 2