2

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
  • What you trying to plot is not a histogram by definition. It's a simple bar chart. Commented May 16, 2018 at 4:47
  • you should use pandas.DataFrame.plot.bar : pandas.pydata.org/pandas-docs/stable/generated/…` Commented May 16, 2018 at 5:04

1 Answer 1

1

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)

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. That works. But I am just wondering why you're plot has multiple colors by default while my plot has only single color?
hmm not sure why default colour behaviour is different, I think it might be version specific (see: stackoverflow.com/questions/45967310/…)
If you want, you can pass in a list of colours to manually control the colour for each bar: stackoverflow.com/questions/18897261/…
the chart in the answer is a bar chart and it is not necessarily a histogram.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.