Micha
Micha

Reputation: 289

matplotlib's xkcd() not working

Ok, I know this question has been asked a lot of times already, but I don't get this working:

I try to use xkcd-style in matplotlib on Ubuntu 16.04 LTS 64-bit with python 2.7.12 64-bit and I use sample code from matplotlib.org/xkcd/examples (see below), but I still get this!

What I've done yet

Any clues how I can get this working? I appreciate any hint!

Greetings, Micha

I use the sample code from matplotlib.org/xkcd/examples:

from matplotlib import pyplot as plt
import numpy as np

plt.xkcd()

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.xticks([])
plt.yticks([])
ax.set_ylim([-30, 10])

data = np.ones(100)
data[70:] -= np.arange(30)

plt.annotate(
    'THE DAY I REALIZED\nI COULD COOK BACON\nWHENEVER I WANTED',
    xy=(70, 1), arrowprops=dict(arrowstyle='->'), xytext=(15, -10))

plt.plot(data)

plt.xlabel('time')
plt.ylabel('my overall health')

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.bar([-0.125, 1.0-0.125], [0, 100], 0.25)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.set_xticks([0, 1])
ax.set_xlim([-0.5, 1.5])
ax.set_ylim([0, 110])
ax.set_xticklabels(['CONFIRMED BY\nEXPERIMENT', 'REFUTED BY\nEXPERIMENT'])
plt.yticks([])

plt.title("CLAIMS OF SUPERNATURAL POWERS")

plt.show()

Upvotes: 9

Views: 1570

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339560

It seems something changed in the way matplotlib uses the context. A working version should be to manually use the context,

with plt.xkcd():
    # your plot here
plt.show()

The example would then read like this:

from matplotlib import pyplot as plt
import numpy as np

with plt.xkcd():
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    plt.xticks([])
    plt.yticks([])
    ax.set_ylim([-30, 10])

    data = np.ones(100)
    data[70:] -= np.arange(30)

    plt.annotate(
        'THE DAY I REALIZED\nI COULD COOK BACON\nWHENEVER I WANTED',
        xy=(70, 1), arrowprops=dict(arrowstyle='->'), xytext=(15, -10))

    plt.plot(data)

    plt.xlabel('time')
    plt.ylabel('my overall health')

plt.show()

enter image description here

This fits with the current version of the example. The example linked to in the question is outdated.

Upvotes: 9

Related Questions