How to generate XKCD plot using Matplotlib

Generate XKCD plot like this by adding a single function call!
Generate XKCD plot like this by adding a single function call!

Don’t you think those plots, charts and graphs used in XKCD comic strips look really cool? I also think that by mimicking handwriting, these plots actually make the data more understandable. But, that’s just me.

Matplotlib now includes support for XKCD plots! And it is really easy to use. If you are already using Matplotlib to generate plots for your data, then you can generate XKCD plots for those easily:

  1. Check if the version of Matplotlib on your computer supports XKCD plots. You can do this with the Python interpreter:
$ python
>>> import matplotlib.pyplot
>>> matplotlib.pyplot.xkcd()
<matplotlib.rc_context object at 0x1ff9950>

If you see the above object being created then your Matplotlib supports XKCD plots. Jump to step 4. If you get a AttributeError: 'module' object has no attribute 'xkcd' error, then you need to build the latest version of Matplotlib from source. See the next two steps.

  1. Before I built Matplotlib, I needed to install the following packages:
$ sudo apt-get install tcl-dev tk-dev
$ sudo pip install --upgrade distribute

I did these because building Matplotlib needs TCL and TK libraries for displaying plots and it needs a recent version of distribute.

  1. Uninstall your existing Matplotlib and use pip to build and install the latest version for you:
$ sudo apt-get remove python-matplotlib
$ sudo pip install matplotlib

Hopefully, that installation should work. If it fails during building then check what libraries its missing and install those packages.

  1. XKCD plots use a font named Humor Sans. Download it from here. To install it follow the steps described here.

  2. You are ready to generate XKCD plots. Just add the call matplotlib.pyplot.xkcd() before the other plotting calls in plot generating Python code. The generated plots will now be like in XKCD!🙂

Tried with: Matplotlib 1.3.0 and Ubuntu 12.04 LTS

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