How to plot a Pandas bar chart with Python ?

In today’s tutorial we’ll learn the basics of charting a bar graph out of a dataframe using Python. If you are using Pandas for data wrangling, and all you need is a simple chart you can use the basic built-in Pandas plots. You can obviously use Matplotlib and Seaborn to draw more elaborated charts as needed.

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:

languagefirst_interviewsecond_interview
1Kotlin70.081.0
2VisualBasic84.075.0
3PHP82.091.0
4Python86.081.0

Side by side 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:

Resize the Pandas chart and adding a title

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

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');

Stacked Python plot with Pandas

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

# stacked pandas 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:

Additional learning