How to plot dictionary data with Python and Pandas?

In this tutorial we will explain how you can easily plot a dictionary with multiple values per key using the very powerful pandas Data Analysis library that is a very popular third party module (not included in the Python standard library).

Step #1: Import Pandas

First and foremost we will enable the pandas library. If Pandas is not installed in your Python development environment, you can easily install it and avoid module not found errors.

One installed, import pandas into your Python program:

import pandas as pd

Step #2: Create a dictionary

We’ll now create the dictionary containing the key value pairs that we would like to plot. We will transform the dictionary to a DataFrame objects. The keys will be transformed to the columns. The values, that are represented by list objects, will become the respective column values.

sales_dict = {
             'area' : ['B2B', 'Online' , 'Retail', 'B2C'],
             'direct' : [441, 463, 382, 409],
            'telesales' : [324, 201, 184, 285]

Step # 3: Create a DataFrame

Next is to initialize a DataFrame:

data = pd.DataFrame(sales_dict)

Let’s look at our dictionary values:


Step #4: Plot a Line Chart

The pandas DataFrame object has lots of useful built-in methods. One of those is the plot() method. We can use the latter in order to render a quick chart showing our DataFrame data:

data.plot(x='area', title = 'Direct vs Tele sales', colormap = 'viridis');

Here’s our simple line plot:

Step #5: Plot a Bar Chart

Plotting a bar chart is similarly easy:

data.plot(kind='bar', x='area', title = 'Direct vs Tele sales', colormap = 'viridis');

Here’s the bar graph:

Creating a stacked bar chart is also possible by passing the stacked=True parameter:

data.plot(kind='bar', x='area', stacked=True, title = 'Direct vs Tele sales', colormap = 'viridis');

And here’s the stacked plot:

Additional learning

How to create and display bar charts with pandas?