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.

Simon
  • 9,762
  • 15
  • 62
  • 119
sealpuppy
  • 615
  • 4
  • 12
  • 27
  • What you trying to plot is not a histogram by definition. It's a simple bar chart. – Klaus D. May 16 '18 at 04:47
  • you should use `pandas.DataFrame.plot.bar` : https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.bar.html` – Dadep May 16 '18 at 05:04

1 Answers1

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

Simon
  • 9,762
  • 15
  • 62
  • 119
  • 1
    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? – sealpuppy May 16 '18 at 06:05
  • hmm not sure why default colour behaviour is different, I think it might be version specific (see: https://stackoverflow.com/questions/45967310/change-colours-of-pandas-bar-chart) – Simon May 16 '18 at 08:02
  • If you want, you can pass in a list of colours to manually control the colour for each bar: https://stackoverflow.com/questions/18897261/pandas-plot-dataframe-barplot-with-colors-by-category – Simon May 16 '18 at 08:02
  • 1
    the chart in the answer is a bar chart and it is not necessarily a histogram. – Kusal Hettiarachchi Oct 29 '20 at 15:58