Software and science can be fun

xkcd is a popular web comic with a strong science/CS/geek focus.


In [1]:
from talktools import website

In [2]:
website('http://xkcd.com/353/')


Out[2]:

xkcd is well known for hand-drawn tables/figures of the type that scientists and engineers draw routinely in the course of their work. Here is comic #1235:

Matplotlib is a popular visualization library for Python. Recently, its developers have added an xkcd mode that automatically displays plots using the hand-drawn visual style of xkcd. Here is the same comic plotted using Python and Matplotlib (credit: Jake Vanderplas, Pythonic Perambulations):


In [3]:
%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 [5]:
xkcd()
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, 'r')

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);


Here are some other examples of Matplotlib's xkcd mode from their gallery:


In [6]:
from matplotlib.ticker import NullFormatter
xkcd()
x = np.random.randn(1000)
y = np.random.randn(1000)
nullfmt   = NullFormatter()         # no labels
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
bottom_h = left_h = left+width+0.02
rect_scatter = [left, bottom, width, height]
rect_histx = [left, bottom_h, width, 0.2]
rect_histy = [left_h, bottom, 0.2, height]
plt.figure(1, figsize=(8,8))
axScatter = plt.axes(rect_scatter)
axHistx = plt.axes(rect_histx)
axHisty = plt.axes(rect_histy)
axHistx.xaxis.set_major_formatter(nullfmt)
axHisty.yaxis.set_major_formatter(nullfmt)
axScatter.scatter(x, y)
binwidth = 0.25
xymax = np.max( [np.max(np.fabs(x)), np.max(np.fabs(y))] )
lim = ( int(xymax/binwidth) + 1) * binwidth
axScatter.set_xlim( (-lim, lim) )
axScatter.set_ylim( (-lim, lim) )
bins = np.arange(-lim, lim + binwidth, binwidth)
axHistx.hist(x, bins=bins)
axHisty.hist(y, bins=bins, orientation='horizontal')
axHistx.set_xlim( axScatter.get_xlim() )
axHisty.set_ylim( axScatter.get_ylim() );



In [7]:
#normal distribution center at x=0 and y=5
x = randn(100000)
y = randn(100000)+5

hist2d(x, y, bins=40)
colorbar();


In IPython, we have also added an xkcdify function that styles an entire Notebook using the xkcd style:


In [8]:
from xkcdify import xkcdify
xkcdify()


Science inherits the attributes of the software used...in this case, fun...