xkcd(tm) in matplotlib? yes!
- Ronak Agrawal
- Aug 31, 2024
- 1 min read

[30th April 2024]
Today I learned that matplotlib has a `plt.xkcd` function. Yeah, our very own plotting library has a plotting function that allows you to generate plots using xkcd's sketch-style comics.
Needless to say, I created a clipart to express my bliss at this realization.

The code for the above comic is as follows.
import matplotlib.pyplot as plt
import numpy as np
with plt.xkcd():
# Based on "Stove Ownership" from XKCD by Randall Munroe
# https://xkcd.com/418/
fig = plt.figure()
ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))
ax.spines[['top', 'right']].set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
ax.set_ylim([-20, 40])
data = np.zeros(100)
data[70:] += np.arange(30)
ax.annotate(
'THE DAY I REALIZED\n matplotlib had a `plt.xkcd` function',
xy=(70, 1), arrowprops=dict(arrowstyle='->'), xytext=(15, -10))
ax.plot(data,c='grey')
ax.set_xlabel('time')
ax.set_ylabel('my mental health')
fig.text(
0.5, 0.05,
'inspired by from xkcd by Randall Munroe',
ha='center')
A couple of things to note if you want to try this yourself.
Looking at the documentation for `plt.xkcd()`, you will note that it uses custom fonts which by default are not packaged with Matplotlib. Install `xkcd script` from here
Signature:
plt.xkcd(
scale: 'float' = 1,
length: 'float' = 100,
randomness: 'float' = 2,
) -> 'ExitStack'
Docstring:
Turn on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode.
This will only have an effect on things drawn after this function is called.
For best results, install the `xkcd script <https://github.com/ipython/xkcd-font/>`_
font; xkcd fonts are not packaged with Matplotlib.
Comments