Skip to content
Advertisement

How to plot histogram for below Data Frame

For example this is the DataFrame

      country_code       ($) millions
0     USA                    181519.23
1     CHN                    18507.58
2     GBR                    11342.63
3     IND                    6064.06
4     CAN                        4597.90

I want to plot the histogram with X axis showing the Countries and the Y axis showing the amounts on the Y axis,

Is this possible.

Advertisement

Answer

For a dataframe that looks like this:

  country_code   millions
0          USA  181519.23
1          CHN   18507.58
2          GBR   11342.63
3          IND    6064.06
4          CAN    4597.90

You can plot the graph you want like so:

# Here, df is your dataframe
# Don't forget to add "from matplotlib import pyplot as plt" at the top of your code
# if you don't have it already.
# ^ this is for the plt.show()

df.plot(x='country_code', y='millions', kind='bar')
plt.show()

This will produce the following plot: enter image description here

You can check more about how pandas’ plot function works in the documentation.

Notes:

While Ibrahim’s answer also works and seaborn is a great library, I’d recommend using pandas’ own plot function if all you want are simple plots like these since seaborn and pandas both depend on matplotlib to draw the plots.
The difference is having 3 libraries as dependencies versus just having two.

Also if you plot doesn’t look like this one, you can try calling plt.tight_layout() before plt.show() to make the image fit better.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement