user13420356
user13420356

Reputation:

How to plot the x-axis of a pandas bar plot in numerical order rather than based on y-axis value

I have a pandas df that looks something like this

,Difference Max
0,12.0
1,1.0
2,-7.0
3,-5.0
4,2.0
5,3.0
6,10.0
7,0.0
8,0.0
9,3.0
10,3.0

from this df I would like to plot a bar chart/histogram showing the number of occurrences for each value in the 'Difference Max' column. I currently have this bar plot enter image description here

using the following code:

df_maxdif['Difference Max'].value_counts().plot(kind='bar')

but I would like to have the x-axis in numerical order from -21 on the leftmost side up to 10 on the rightmost side. I've tried simply plotting kind = 'hist' but its not quite what I'm looking for.

Upvotes: 3

Views: 1139

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150725

Chain value_counts() with sort_index:

df_maxdif['Difference Max'].value_counts().sort_index().plot(kind='bar')

Or use plt.hist:

plt.hist(df['Difference Max'], bins=np.arange(-21,10))

Output (for plt.hist):

enter image description here

Upvotes: 5

Related Questions