How to plot a Python dictionary with Seaborn?

To draw a Seaborn plot from a dictionary data make sure to follow the steps outlined below

Step 1: Import Pandas and Seaborn

Out first step will be to import the 3rd party packages we will be working with today: pandas and Seaborn. Type the following command into your Jupyter Notebook , Colab, PyCharm or other Python dev environment you are using:

import pandas as pd
import seaborn as sns

Make sure both are correctly installed in your development environment before moving on.

Step 2: Build your dictionary

Next, we will quickly define a dictionary object . In this example, we will create a few Python lists and use them to build the campaign dictionary:

month = ['March', 'July', 'July', 'September', 'November', 'December']
language = ['R', 'R', 'Python', 'Python', 'R', 'R']
interviews = [13, 12, 8, 14, 19, 15]
campaign = dict(month = month, language = language, interviews = interviews)

Steps 3: Create a DataFrame

Now that we have our dictionary, we can go ahead and create a pandas DataFrame that we will use to feed Seaborn with:

hrdf = pd.DataFrame(data=campaign)

The DataFrame contains and index column and 3 data columns:

print(hrdf)
monthlanguageinterviews
0MarchR13
1JulyR12
2JulyPython8
3SeptemberPython14
4NovemberR19
5DecemberR15

Step 4: Plot a Seaborn chart

Next, we will go ahead and render a bar chart using Seaborn.

bar = sns.barplot(data = hrdf, x = 'language', y= 'interviews', hue = 'month', palette = 'Paired'); #1
bar.set_title("Interview metrics"); #2
bar.legend(bbox_to_anchor= (1.01, 1)); #3

Explanation:

  • Row #1 defines the barplot object. It assigns the DataFrame that we have created to the chart, links the respective DataFrame columns to the axis and define a color palette.
  • Row #2 defines a title for the plot
  • Row #3 adjusts the legend placement to the right hand side of the chart.

This will create the following bar plot.

Note: We can use similar techniques to build any kind of Searborn charts such as histograms, column charts, box plots etc’.