Skip to main content

XKCD Plots in Matplotlib: Going the Whole Way

http://jakevdp.github.io/blog/2013/07/10/XKCD-plots-in-matplotlib/

One of the most consistently popular posts on this blog has been my XKCDify post, where I followed in the footsteps of others to write a little hack for xkcd-style plotting in matplotlib. In it, I mentioned the Sketch Path Filter pull request that would eventually supersede my ugly little hack.
Well, "eventually" has finally come. Observe:
In [1]:
%pylab inline
Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.kernel.zmq.pylab.backend_inline].
For more information, type 'help(pylab)'.

In [2]:
plt.xkcd()  # Yes...
plt.plot(sin(linspace(0, 10)))
plt.title('Whoo Hoo!!!')
Out[2]:
<matplotlib.text.Text at 0x2fade10>
The plt.xkcd() function enables some rcParam settings which can automatically convert any matplotlib plot into XKCD style. You can peruse the matplotlib xkcd gallery here for inspiration, or read on where I'll show off some of my favorite of the possibilities.
By the way, this new functionality requires matplotlib version 1.3, which can currently be downloaded and installed from github. Also, if you want to have the font match above, be sure to download and install the Humor Sans font on your system. For matplotlib to recognize it, you may have to remove the font cache, found on your system at
Even simple plots can be made much more interesting:
In [3]:
x = np.linspace(0, 10)
y1 = x * np.sin(x)
y2 = x * np.cos(x)

plt.fill(x, y1, 'red', alpha=0.4)
plt.fill(x, y2, 'blue', alpha=0.4)
plt.xlabel('x axis yo!')
plt.ylabel("I don't even know")
Out[3]:
<matplotlib.text.Text at 0x31e3190>
3D plots work as well:
In [4]:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

x = np.linspace(0, 10, 30)
colors = ['r', 'g', 'b', 'y']
y = np.random.random((len(colors), len(x)))
y[:, 0] = y[:, -1] = 0

edges = [list(zip(x, yi)) for yi in y]

poly = PolyCollection(edges, facecolors=colors, alpha=0.6)
ax.add_collection3d(poly, zs=range(4), zdir='y')

ax.set_xlabel('X')
ax.set_xlim3d(0, 10)
ax.set_ylabel('Y')
ax.set_ylim3d(-1, 4)
ax.set_zlabel('Z')
ax.set_zlim3d(0, 1)
/home/vanderplas/PythonEnv/pydev/local/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/axis.py:695: MatplotlibDeprecationWarning: This function has been made private and movedto `_set_scale`. This wrapper function will be removed in 1.4
  "removed in 1.4", mplDeprecation)

Out[4]:
(0, 1)
We can use the new package to quickly reproduce a recent XKCD comic:
In [5]:
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(211)

years = np.linspace(1975, 2013)
pct = 2 + 98. / (1 + np.exp(0.6 * (2008 - years)))
ax.plot(years, pct)

ax.set_xlim(1976, 2013)
ax.set_ylim(0, 100)
ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%i%%'))

ax.text(1977, 67,
        ("Percentage of the US Population\n"
         "carrying cameras everywhere they go,\n"
         "every waking moment of their lives:"),
        size=16)

ax.set_xlabel(("In the last few years, with very little fanfare,\n"
               "We've conclusively settled the questions of\n"
               "flying saucers, lake monsters, ghosts, and bigfoot."),
              size=16)
Out[5]:
<matplotlib.text.Text at 0x35adc90>
And as my favorite example, we can recreate any of the animations I've shown in this blog, making them xkcd-style with a simple plt.xkcd() annotation. Below you can see the double-pendulum animation from this post, rendered using the XKCD sketch path:
In [6]:
from IPython.display import HTML
url = 'http://jakevdp.github.io/downloads/videos/double_pendulum_xkcd.mp4'
HTML('<video controls alt="animation" src="{0}">'.format(url))
Out[6]:
The code used to create this movie can be downloaded here
This addition to matplotlib is much more flexible than the little hack I wrote last fall; I hope you have fun playing with it. And as someone quipped at the Scipy conference in June, "First one to get an XKCD plot in a Nature paper wins!"
This post was written entirely as an IPython notebook. The full notebook can be downloaded here, or viewed statically on nbviewer

Comments

Popular posts from this blog

The Difference Between LEGO MINDSTORMS EV3 Home Edition (#31313) and LEGO MINDSTORMS Education EV3 (#45544)

http://robotsquare.com/2013/11/25/difference-between-ev3-home-edition-and-education-ev3/ This article covers the difference between the LEGO MINDSTORMS EV3 Home Edition and LEGO MINDSTORMS Education EV3 products. Other articles in the ‘difference between’ series: * The difference and compatibility between EV3 and NXT ( link ) * The difference between NXT Home Edition and NXT Education products ( link ) One robotics platform, two targets The LEGO MINDSTORMS EV3 robotics platform has been developed for two different target audiences. We have home users (children and hobbyists) and educational users (students and teachers). LEGO has designed a base set for each group, as well as several add on sets. There isn’t a clear line between home users and educational users, though. It’s fine to use the Education set at home, and it’s fine to use the Home Edition set at school. This article aims to clarify the differences between the two product lines so you can decide which

Let’s ban PowerPoint in lectures – it makes students more stupid and professors more boring

https://theconversation.com/lets-ban-powerpoint-in-lectures-it-makes-students-more-stupid-and-professors-more-boring-36183 Reading bullet points off a screen doesn't teach anyone anything. Author Bent Meier Sørensen Professor in Philosophy and Business at Copenhagen Business School Disclosure Statement Bent Meier Sørensen does not work for, consult to, own shares in or receive funding from any company or organisation that would benefit from this article, and has no relevant affiliations. The Conversation is funded by CSIRO, Melbourne, Monash, RMIT, UTS, UWA, ACU, ANU, ASB, Baker IDI, Canberra, CDU, Curtin, Deakin, ECU, Flinders, Griffith, the Harry Perkins Institute, JCU, La Trobe, Massey, Murdoch, Newcastle, UQ, QUT, SAHMRI, Swinburne, Sydney, UNDA, UNE, UniSA, UNSW, USC, USQ, UTAS, UWS, VU and Wollongong.

Building a portable GSM BTS using the Nuand bladeRF, Raspberry Pi and YateBTS (The Definitive and Step by Step Guide)

https://blog.strcpy.info/2016/04/21/building-a-portable-gsm-bts-using-bladerf-raspberry-and-yatebts-the-definitive-guide/ Building a portable GSM BTS using the Nuand bladeRF, Raspberry Pi and YateBTS (The Definitive and Step by Step Guide) I was always amazed when I read articles published by some hackers related to GSM technology. H owever , playing with GSM technologies was not cheap until the arrival of Software Defined Radios (SDRs), besides not being something easy to be implemented. A fter reading various articles related to GSM BTS, I noticed that there were a lot of inconsistent and or incomplete information related to the topic. From this, I decided to write this article, detailing and describing step by step the building process of a portable and operational GSM BTS. Before starting with the “hands on”, I would like to thank all the pioneering Hackers and Researchers who started the studies related to previously closed GSM technology. In particul