5 Steps to Amazing Visualizations with Matplotlib
By: Dario Radečić
Tags: Data Visualization, Programming, Data Science, Matplotlib, Python

We’ve all been there. Matplotlib is imported, your dataset is prepared, and you are ready to make some astonishing visualization. Pretty soon, the harsh reality of potato-looking default Matplotlib charts hits you in the face.

Damn.

A couple of weeks ago I’ve written about taking your visualizations to the next level by developing interactive dashboard applications with Flask and Bokeh:

That article was far more complex than this one will be, but I still wanted to point it out if you ever need something more flexible.

Today I will show you 5 things I do with most of the visualizations in Matplotlib, in a hope that you will realize that there’s no real benefit of jumping into Seaborn or Bokeh straight away — for most cases Matplotlib has you covered.

Dataset Introduction

For this guide, I’ve used kc_house_data dataset available on Kaggle. The main reason for choosing this one from the ocean of others is that it contains a good amount of observations, but more importantly, it contains 2 attributes that should be highly correlated:

Living Area

Price

and due to potential correlation, a nice scatter plot can be drawn.

If you don’t feel like downloading the dataset and following along, here’s how the head of the dataset looks like:

Head of kc_house_data.csv

But before jumping into visualizations, here is the code for the imports and basic setup:

Imports and Setup — https://gist.github.com/dradecic/43729ca53567fa44e433130faebeeb6d

I’ve chosen to sample 100 points from the dataset because, in general, scatter plots don’t look good when there are too many data points.

Then, I’ve set x to represent the living area, and y to represent the house price.

The initial plotting is very simple now:

Default Matplotlib scatter plot — https://gist.github.com/dradecic/bfa07c255be6d7eafba74f001d6a9eb5

Executing this cell will yield an unsatisfying, boring, and ugly looking chart:

Default Matplotlib scatter plot

Luckily, there’s a lot you can do about it. Here is the list of 5 points this article will be based upon:

Removing Spines Adding Custom Font to Title and Axis Labels Adding Units to Axis Labels Changing Marker, Color, Size, and Opacity Adding Annotations

Without further ado, let’s dive straight into the first point.

1. Remove Spines

Charts in Matplotlib are shown in a ‘box’ which looks very restrictive, to say at least. Other visualization libraries are by default more open-looking, and this effect can be easily achieved here.

The goal here is to remove the top horizontal bar and right vertical bar.

It is achieved by adding the following to your chart code cell:

Removing Spines — https://gist.github.com/dradecic/a96645c8798e556d1379bad2216bf895

Removing spines

Voilà! The chart is now more open, and therefore, more appealing.

2. Add Custom Font to Title and Axis Labels

Now, this process will be a bit more tedious than the first one. I’ve chosen to use Raleway font, and you will need to download zipped .ttf if you don’t already have it.

Once downloaded, extract TTF-s to your Matplolib’s folder. If you are using Anaconda like me, the path on Windows will be as follows:

C:\Users\<YOUR-USER-NAME>\AppData\Local\Continuum\anaconda3\Lib\site-packages\matplotlib\mpl-data\fonts\ttf

You can now access any downloaded font directly through Jupyter and Matplotlib.

In a new cell, paste the following code (I’ve chosen Semi-Bold Italic for title and Light-Italic for axis labels):

Fonts Setup — https://gist.github.com/dradecic/a8b85ca866e7ac1543a362247feac80d

Now you can add the following code to your chart cell, just before calling .scatter().

Note how you can use LaTeX when setting the title and/or axis labels. By doing so you can avoid weird looking charts if the text on them should represent some unit, square feet for example.

Title and Axis Labels — https://gist.github.com/dradecic/aa873a492a17b46da590370379853f24

And this is how your chart will look like now:

Title and axis labels with custom font

Not too bad for a couple of lines of code. But you can do better.

3. Add Units to Axis Labels

There really is no point in further explanation of what this point is all about.

You want axis labels to be more appealing. Period.

The process of achieving this isn’t as straightforward as in other visualization libraries, but it is manageable. Anyway, here’s the code:

Axis Units — https://gist.github.com/dradecic/71d0408606239e4ce7d9ddc37e646c79

The code above will add a thousand separator for both axis labels.

Further, on the x-axis, the unit is feet squared, so that’s what will be added.

On the y-axis, the unit is in American Dollars. Ticks are formatted as money, having comma as a thousand separator and dot as a cents separator.

Added units to tick labels

4. Change Marker, Color, Size, and Opacity

You didn’t actually think that I will skip this one — did you?

Probably the most obvious, and in most scenarios, the first thing you do is to alter marker size, shape, and color.

Here I’ve used a reversed triangle as the marker, and some dark blue as the marker color.

Due to a large concentration of data points on pretty much the same location, opacity should be lowered so you can see the points more clearly.

Anyway, here’s the code for achieving this:

Marker, Size, Color, and Opacity — https://gist.github.com/dradecic/14d62e2cddda2e0cc34e6d90e2174977

Changing markers

Almost done. But not just yet.

5. Add Annotations

At last, it’s a good idea to print the correlation coefficient on a scatter plot, if it makes sense (if the variables are correlated). If you do that, by default you will have a marker to the left of the legend text.

That’s not what you want here, you want a simple, clear, and visible text-only representation of correlation coefficient.

First, you’ll need to calculate it. It’s pretty simple to do with Numpy, and for this case, I will round the result up to two decimal points. You will then need to pass the label to .scatter() call and hide every legend handle that exists.

There’s a bit of code for doing so, but it’s not complicated.

Adding annotations

And that is how your final chart looks like. Pretty nice for a couple of minutes work!

If you’ve got lost in the process, don’t worry, here’s the entire code snippet:

Conclusion

This isn’t a definitive guide to Matplotlib. It was written with having average Joe in mind — not the complete beginner, but not the expert either.

I hope you can now see the power of Python’s most popular visualization library, and that next time you won’t jump into Seaborn or Bokeh immediately.

Thanks for reading.

Until next time…