Python Friday #170: XKCD Styled Plots for Matplotlib

Over the last weeks we got a few nice visualisations out of Matplotlib. But what can we do when we only have temporary data that should not be shared? Is there a way to make it clear that this plot is a stand-in and not the final product?

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

XKCD?

XKCD is a webcomic created by Randall Munroe. He uses a lot of diagrams in his comics and in his books. A good example for his style is the comic on automation that you can find here: https://xkcd.com/1319/

XKCD on automation

Matplotlib has a built-in XKCD feature that we can use. The only parts that we need to install are the fonts.

 

Install the fonts on Windows

To get an XKCD styled figure we need these four fonts:

After the download, you can double-click on the files to open the font preview tool. This tool has an install button that will put the fonts at the right places on Windows so that the applications can use the fonts.

 

Clear the Matplotlib cache

After you installed the fonts, you need to find the Matplotlib cache. You can run this command in a notebook:

This should give you a folder that you can open in the file explorer. Inside the folder should be a single JSON file (like fontlist-v330.json). Delete that JSON file or rename it. The next time you run Matplotlib, this file will be recreated – this time with your newly installed fonts.

 

Use the XKCD style

We can use the XKCD style in a with block, but with a different syntax from the other styles:

This turns our familiar graph into something that screams draft:

Our bar chart in the XKCD style

 

Next

With the XKCD style we can turn our figures into something that looks like a comic. This should make it clear that this plot is not in its final form, and we do not need to spend extra time for creating mock plots. Next week we add annotations to our plots to point out important parts.

1 thought on “Python Friday #170: XKCD Styled Plots for Matplotlib”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.