Skip to content

xkcd Plot Styles

To generate plots that look hand drawn, in the style of the xkcd comic, we can use the plt.xkcd() styling option. To make the style only temporary we construct the plot under a with statement to limit the scope of the styling.

with plt.xkcd():
    # This figure will be in XKCD-style
    fig, axes = plt.subplots(1, 3, figsize=(12, 4))

    axes[0].plot(x, x**2, x, x**3)
    axes[0].set_title("default axes ranges")

    axes[1].plot(x, x**2, x, x**3)
    axes[1].axis('tight')
    axes[1].set_title("tight axes")

    axes[2].plot(x, x**2, x, x**3)
    axes[2].set_ylim([0, 60])
    axes[2].set_xlim([2, 5])
    axes[2].set_title("custom axes range")

Graph Graph

The text will be displayed in 'comic sans' (I don't have the font available in my jupyter notebook).

Here is another example.

with plt.xkcd():
    x = np.linspace(0, 1, 100)
    y = (x > 0.5) * (x - 0.5)

    plt.xkcd(scale=5, length=400)
    plt.xticks([])
    plt.yticks([])
    plt.ylabel('Downloads of "humor sans" font')
    plt.text(0, 0.25, 'Article on xkcd() published')
    plt.plot(x, y)
    plt.plot([0.3, 0.475], [0.2, 0.025], 'black')
    plt.gca().set_aspect(2*9/16)
    #plt.savefig('xkcd_plot.png', dpi=300)

Graph Graph