How to get XKCD font working in Matplotlib?

To get XKCD font working in Matplotlib, we can use plt.xkcd() to turn on sketch-style drawing mode. This creates hand-drawn style plots similar to the popular XKCD webcomic.

Steps

  • Set the figure size and adjust the padding between and around the subplots
  • Create x and y data points using numpy
  • Use plt.xkcd() to turn on sketch-style drawing mode
  • Create a new figure or activate an existing figure
  • Add an axis to the figure as part of a subplot arrangement
  • Plot x and y data points using plot() method
  • Place text and title on the plot
  • To display the figure, use show() method

Example

Here's how to create a hand-drawn style plot using XKCD font ?

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.arange(10)
y = np.sin(x)

plt.xkcd()

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
ax.text(4, 0.5, '(4, 0.5)', size=16)

plt.title('Y=sin(x)')
plt.show()

Advanced Example

You can also customize the sketch style with additional parameters ?

import matplotlib.pyplot as plt
import numpy as np

# Enable XKCD style with custom parameters
plt.xkcd(scale=1, length=100, randomness=2)

x = np.linspace(0, 10, 100)
y = np.cos(x) * np.exp(-x/5)

plt.figure(figsize=(10, 6))
plt.plot(x, y, linewidth=2)
plt.title('Damped Cosine Wave - XKCD Style', fontsize=16)
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.grid(True, alpha=0.3)
plt.show()

Parameters

The plt.xkcd() function accepts the following optional parameters:

  • scale − Controls the amplitude of the wiggle perpendicular to the source line (default: 1)
  • length − Controls the length of the wiggle along the line (default: 100)
  • randomness − Controls the scale factor for the random wiggle (default: 2)

Disabling XKCD Mode

To return to normal plotting style, use matplotlib.rcdefaults() ?

import matplotlib.pyplot as plt
import matplotlib
import numpy as np

# First, enable XKCD mode
plt.xkcd()
x = np.arange(5)
y = x ** 2

plt.figure(figsize=(12, 4))

plt.subplot(1, 2, 1)
plt.plot(x, y)
plt.title('XKCD Style')

# Reset to default style
matplotlib.rcdefaults()

plt.subplot(1, 2, 2)
plt.plot(x, y)
plt.title('Default Style')

plt.tight_layout()
plt.show()

Conclusion

Use plt.xkcd() to create hand-drawn style plots that mimic the XKCD webcomic aesthetic. Customize the sketch parameters for different visual effects, and use matplotlib.rcdefaults() to return to normal plotting style.

Updated on: 2026-03-25T23:43:14+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements