James Smith
James Smith

Reputation: 125

How to use column values for x axis labels in matplotlib

I have a basic DataFrame in pandas and using matplotlib to create a chart

I have followed advice found on SO and also on the docs for labelling the values on the x axis but they won't change from the indices.

I have this,


Presc_df_asc = Presc_df.sort_values('Total Items',ascending=True)
Presc_df_asc['Total Items'].plot.bar(x="Practice", ylim=[Presc_df_asc['Total Items'].min(), Presc_df_asc['Total Items'].max()])
plt.xlabel('Practice')
plt.ylabel('Total Items')
plt.title('practice total items')
plt.legend(('Items',),loc='upper center')

From what I have found plot.bar(x="Practice" should set the x-axis to show the values int he practice column under each bar.

But no matter what I try I get the x-axis labelled as indices with just the main label saying Practices.

Upvotes: 0

Views: 1353

Answers (1)

BenB
BenB

Reputation: 658

In order for the plotting command to be able to access the "Practice" column, you need to apply the plot function to the entire dataframe (or a sub_dataframe that contains at least these two columns). The code below uses the corresponding labels below each bar. The rot=0 argument prevents the labels from being rotated by 90°.

Presc_df_asc.plot.bar(x="Practice", y ="Total Items", 
                    ylim=[Presc_df_asc['Total Items'].min(), 
                    Presc_df_asc['Total Items'].max()], rot=0)

Upvotes: 1

Related Questions