How to plot a Pandas bar chart from a DataFrame in Python?

In this 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.

Create Bar plot from Pandas DataFrame

Proceed as following to plot a bar chart in pandas:

  • Create a pandas DataFrame from a file, database or dictionary.
  • Use the DataFrame plot() method to define your chart.
  • Customize your chart as needed by resizing it, add a legen, set your chart tile, set your axes ticks labels, etc’.

Importing data to the Python DataFrame

We’ll start with creating a pandas 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 hr interview data:


Make a Bar graphs 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 very simple side by side bar chart:

Resize Pandas charts 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