How to plot a bar chart with Python and Pandas?

In today’s tutorial we’ll learn the basics of charting a bar graph out of data in a dataframe using Python. We typically use Matplotlib and Seaborn to draw charts, but today we’ll look into the limited by pretty useful plotting capabilities that are already included in the Pandas Data Analysis library.

Bar plot in Python example

Importing data to the Python DataFrame

We’ll start with creating a dataframe by importing data using the read_csv() method.

import pandas as pd

my_df =  pd.read_csv('interviews.csv')

print (my_df)

Here’s our dataframe populated with some fictitious interview data:


Rendering a bar chart from a dataframe

If we want to create a simple chart we can use the df.plot() method. Note that we’ll use the kind= parameter in order to specify the chart type. Several graphs are available such as histograms, pies, area, scatter, density etc’.

my_df.plot(kind='bar' , x='language');

Here’s the early version of our ver simple chart:

Resizing the Pandas chart and adding a title

Modifying the chart size is easy with the figsize parameter. We are also use the title parameter to define the chart header.

my_df.plot(kind='bar' , x='language', title='Interviews per month', figsize= (11,6));

Here’s the chart:

Making an horizontal Python graph

By using the barh chart type, we can transpose the graph rendering.

my_df.plot(kind='barh' , x='language', title='Interviews per month');

Make a stacked Python plot

We can easily stack our bars chart as needed using the stacked parameter.

# stacked bar graph
my_df.plot(kind='bar' , x='language', stacked=True, figsize= (11,6));

Here’s the chart:

Change the color of our Python chart

The DataFrame.plot() method also delivers capability to map the chart to a known color map (cmap). Here’s an example:

#change color maps
my_df.plot(kind='bar' , x='language', stacked=True, cmap='Dark2',figsize= (11,6));

And here’s the chart:

Modify the chart axes labels

We can also change the style of the axes labels. In this example we rotate the x-axis labels and enlarge the label font size.

my_df.plot(kind='bar' , x='language', stacked=True, cmap='Dark2', rot=30, fontsize=13, figsize= (11,6)));

And here’s the output: