Creating XKCD Graphics in python

I was recently browsing through the functions available in matplotlib’s pyplot and stumbled upon a rather interesting “xkcd” function.

It turns out can format your charts into an XKCD style plot – which is really cool. It definitely could help lighten the mood if used in a presentation. One guy argues it could also be used to help convey information on the quality of data or methods used, especially for back-of-the-envelope calculations.

You can test the feature out with this demo.

import matplotlib.pyplot as plt
from numpy import sin,cos,linspace


plt.title("My first XKCD")


You can check out some other cool examples and associated code here and here for inspiration.


Running it in Linux

The script above runs straight out of the box in windows. However, linux does not have the comic sans font or its alternatives, so the text would come out looking odd.

To fix this, download Humour-sans or Comic-sans and open a terminal. Type

sudo nautilus

to open a file explorer window as root.

Navigate to /usr/share/fonts/truetype in the file explorer and create a new folder in the name of the font you want to install eg humour-sans.

Now copy the ttf file you downloaded into the new folder.

Clear matplotlib’s font cache by deleting the fontList.cache file in ~/.cache/matplotlib

You should now be able to run the examples without issue.

Also, to ensure you don’t get locked in to that design so that you can safely switch to the default design in your scripts, this post advised use it with a with statement.

with plt.xkcd():
    #plot your stuff in the xkcd style

#continue your script while plotting with the default style

Have fun.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s