Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

python - Pandas DataFrame bar plot with sort_values by other column

I have a Pandas DataFrame. I want to plot two columns' values with bar plot, and the bar plot sorts values by the other column.

For example, I want to sort values in descending order by column a_b(sum of column a and b). In addition, the xlabel is rotated, I want to fix it.

Your help would be appreciated.

import pandas as pd
%matplotlib inline
a = pd.Series([4,8,6,7,8,3,9,7])
b = pd.Series([3,6,8,3,4,6,10,4])
a_b = a+b
df = pd.concat([a,b,a_b],axis=1,join='inner')
df.columns = ['a','b','c']

df[['a','b']].sort_values(by='a',ascending=False).plot(kind='bar',stacked=True)

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Sort dataframe first by c then plot with.

df.sort_values('c', ascending=False)[['a','b']].plot.bar(stacked=True)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...