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:


Can i plot a dictionary as scatter, histogram and other pandas chart types?

Yes, once you convert your dictionary to a pandas DataFrame, you can easily plot it not only as line or bar charts; but also as an histogram, scatter, pie, box plot, area plots etc’. You can also use additional 3rd party visualization libraries such as Seaborn and Matplotlib to produce more sophisticated visuals – such as heatmaps.

What are the plot components that i can customize?

You can customize the look and feel of several of your plot components such as : title, background color, size, fonts, line style, markers and legend.

Can i save the plot to a file instead of showing it in a screen?

Use the following command to save your plot to an image file (jpg,bmp,png):


What if columns representing numbers contain text or string data?

Before plotting your data you will need to convert it to non numeric:

my_df['my_col'] = pd.to_numeric(my_df['my_col'], errors = 'coerce')

Additional learning

How to create and display bar charts with pandas?