Plot a Histogram Sort by Values in Python

Plot a Histogram Sort by Values in Python

I have a Pandas dataframe as following:

              number
Art           10000
Comics        235
Crafts        293
Dance         824

How can I plot a histogram that sort by values?

Demonstration:

*
* *
* *
* *
* *
* * * *
* * * *
-------------
x labels = Art/ Dance/ Crafts/ Comics

I have tried pandas.DataFrame.hist, but not sure how to select proper arguments.

2

1 Answer

You can just sort your dataframe first and then create the plot using your dataframes plot method

Test data (I set category as the index as thats what it looks like you have for your actual data):

import pandas as pd

df = pd.DataFrame({'category': ['Art', 'Comics', 'Crafts', 'Dance'],
                   'number': [10000, 235, 293, 824]})
df.set_index('category', inplace=True)

          number
category        
Art        10000
Comics       235
Crafts       293
Dance        824

Then sort by number using df.sort_values() and call df.plot():

df.sort_values('number', inplace=True)

df.plot(y='number', kind='bar', legend=False)
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.