Home > Back-end >  sorting out my horizontal bar chart in pandas
sorting out my horizontal bar chart in pandas

Time:04-07

I have been trying to visualize some data and put them on horizontal bar charts stacked over each other.

when doing so, I find it hard to sort them based on their sizes, which I wanted.

I have tried sorting the date before visualizing it but that didn't help.

could someone please help me sort them des. thanks

import pandas as pd 

import matplotlib.pyplot as plt

df = pd.read_csv("data.csv")

plot3 = df.groupby(['Company', 'Outcome']).size()
plot3 = plot3.unstack()
plot3[:].sort_values(('Company'), axis = 0, ascending = True).plot(kind = 'barh',color = ['r', 'g'],figsize = [15, 10], stacked = True)
#df= df.sort_values('Company', axis = 0, ascending = True,inplace = True)
    
plt.savefig('plot3.png')'''



[![here is what i get][1]][1]



  [1]: https://i.stack.imgur.com/WkvY9.jpg

CodePudding user response:

You can sorting summed rows by DataFrame.sort_index with key parameter and scending=False:

(plot3.sort_index(key=plot3.sum(axis=1).get, ascending=False)
      .plot(kind = 'barh',color = ['r', 'g'],figsize = [15, 10], stacked = True))

Or use DataFrame.iloc with Series.argsort, - for negative values is for descending order:

(plot3.iloc[-plot3.sum(axis=1).argsort()]
      .plot(kind = 'barh',color = ['r', 'g'],figsize = [15, 10], stacked = True))
  • Related