A Beginner’s Guide to Data Visualization Using Matplotlib
By: Reilly Meinert
Tags: Visualization, Data Visualization, Data Science, Matplotlib, Pytho

A Beginner’s Guide to Data Visualization Using Matplotlib

Introduction

The purpose of this article is to provide a very brief introduction to using Matplotlib, one of the most commonly used plotting libraries in Python. By the end of this walkthrough, you’ll know how to make several different kinds of visualizations and how to manipulate some of the aesthetics of a plot. The data used in this tutorial can be found here. This particular dataset comes from data gathered by the World Health Organization, and it contains information that is used to calculate the Happiness Score of a particular country, such as a country’s GDP, life expectancy, and the people’s perception of how corrupt the country’s government is.

Prior to creating our graphs, let’s import the necessary libraries and check out the dataset:

import pandas as pd

import matplotlib.pyplot as plt df = pd.read_csv('WorldHappiness2018_Data.csv')

df.head()

From this, we see that the dataset is ordered based on the country’s overall rank in terms of their happiness score. The rest of the columns after ‘Score’, to include ‘Residual’ which is not shown here, are summed up to get the total happiness score for a country. It would make sense then to expect higher values in each of the individual columns to generally indicate a higher overall happiness score for a country.

Line Graphs

Line graphs are probably the simplest graph one can create using Matplotlib. Let’s create a graph to see the relationship between a country’s rank and their happiness score. We would expect that the highest ranking country (ranked closest to 1) would have the highest happiness score, and the lowest ranking country would have the lowest score. We can create this visualization with four simple lines of code.

rank = df['Rank']

score = df['Score']

These two lines of code subset the dataframe. The first creates a Series that only contains the overall rank for each country. The second creates a Series that only contains the happiness score for each country. Because this information was pulled from a dataframe, you can assume that all data will be held at their original index, and the data will then line up properly.

plt.plot(rank, score)

plt.show()

These next two lines of code create the actual plot. The plt.plot() command creates a line graph, and the parameters passed in tell the function what data to use. The first, rank, will be plotted on the x-axis, and the second, score, will be plotted on the y-axis. Calling plt.show() is required for your graph to actually be printed onto your screen. When run, the output will be as follows:

It was simple enough to create this graph, and it shows us exactly what we were expecting to see. However, there are a few problems with this graph. If you weren’t the one who created it, or if you are looking back at it a while after you created it, you’ll have no idea what this graph is actually showing. Luckily, adding a title and axes labels is pretty simple.

plt.plot(rank, score)

plt.title('Happiness Score vs World Rank')

plt.xlabel('Country Rank')

plt.ylabel('Country Score')

plt.show()

These commands are pretty self-explanatory, and the result is much easier to interpret than the first graph.

It was simple enough to add labels and a title to our original line graph, and it improves its appearance drastically. Not only is it more professional to have a labeled graph, it also makes it much easier to understand what the graph is showing us with little extra context or extra explanation required. Now, what happens if we want to examine more than one variable’s relationship with the rank of a country on the same graph? All you have to do is call plt.plot() twice with the two different series that you’d like to pass as the parameters for the x-value, as shown here:

gdp = df['GDP_Per_Capita']

lifeExp = df['Healthy_Life_Expectancy'] plt.plot(rank, gdp)

plt.plot(rank, lifeExp)

plt.show()

This code outputs the following visual:

Like the first graph we made, we don’t really know what this graph is telling us. Additionally, we don’t know which line represents which x-parameter we passed in. There are two possible ways to handle this issue. The first will add a legend to tell us what color line represents which variable.

# Option 1

plt.plot(rank, gdp)

plt.plot(rank, lifeExp)

plt.title('World Rank vs GDP and Life Expectancy')

plt.xlabel('Country Rank')

plt.legend()

plt.show() # Option 2 plt.plot(rank, gdp, color = 'green')

plt.plot(rank, lifeExp, color = 'blue')

plt.title('World Rank vs GDP and Life Expectancy')

plt.xlabel('Country Rank')

plt.legend()

plt.show()

Note: These options should be ran separately from each other in order to get both outputs.