Skip to content

Commit a274a41

Browse files
committed
Provide xkcd as a context manager
1 parent 9652004 commit a274a41

File tree

3 files changed

+84
-66
lines changed

3 files changed

+84
-66
lines changed

examples/showcase/xkcd.py

Lines changed: 41 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,45 @@
1-
from matplotlib import pyplot as plt
1+
import matplotlib.pyplot as plt
22
import numpy as np
33

4-
plt.xkcd()
5-
6-
# Based on "Stove Ownership" from XKCD by Randall Monroe
7-
# http://xkcd.com/418/
8-
9-
fig = plt.figure()
10-
ax = fig.add_subplot(1, 1, 1)
11-
ax.spines['right'].set_color('none')
12-
ax.spines['top'].set_color('none')
13-
plt.xticks([])
14-
plt.yticks([])
15-
ax.set_ylim([-30, 10])
16-
17-
data = np.ones(100)
18-
data[70:] -= np.arange(30)
19-
20-
plt.annotate(
21-
'THE DAY I REALIZED\nI COULD COOK BACON\nWHENEVER I WANTED',
22-
xy=(70, 1), arrowprops=dict(arrowstyle='->'), xytext=(15, -10))
23-
24-
plt.plot(data)
25-
26-
plt.xlabel('time')
27-
plt.ylabel('my overall health')
28-
29-
# Based on "The Data So Far" from XKCD by Randall Monroe
30-
# http://xkcd.com/373/
31-
32-
fig = plt.figure()
33-
ax = fig.add_subplot(1, 1, 1)
34-
ax.bar([-0.125, 1.0-0.125], [0, 100], 0.25)
35-
ax.spines['right'].set_color('none')
36-
ax.spines['top'].set_color('none')
37-
ax.xaxis.set_ticks_position('bottom')
38-
ax.set_xticks([0, 1])
39-
ax.set_xlim([-0.5, 1.5])
40-
ax.set_ylim([0, 110])
41-
ax.set_xticklabels(['CONFIRMED BY\nEXPERIMENT', 'REFUTED BY\nEXPERIMENT'])
42-
plt.yticks([])
43-
44-
plt.title("CLAIMS OF SUPERNATURAL POWERS")
4+
with plt.xkcd():
5+
# Based on "Stove Ownership" from XKCD by Randall Monroe
6+
# http://xkcd.com/418/
7+
8+
fig = plt.figure()
9+
ax = fig.add_subplot(1, 1, 1)
10+
ax.spines['right'].set_color('none')
11+
ax.spines['top'].set_color('none')
12+
plt.xticks([])
13+
plt.yticks([])
14+
ax.set_ylim([-30, 10])
15+
16+
data = np.ones(100)
17+
data[70:] -= np.arange(30)
18+
19+
plt.annotate(
20+
'THE DAY I REALIZED\nI COULD COOK BACON\nWHENEVER I WANTED',
21+
xy=(70, 1), arrowprops=dict(arrowstyle='->'), xytext=(15, -10))
22+
23+
plt.plot(data)
24+
25+
plt.xlabel('time')
26+
plt.ylabel('my overall health')
27+
28+
# Based on "The Data So Far" from XKCD by Randall Monroe
29+
# http://xkcd.com/373/
30+
31+
fig = plt.figure()
32+
ax = fig.add_subplot(1, 1, 1)
33+
ax.bar([-0.125, 1.0-0.125], [0, 100], 0.25)
34+
ax.spines['right'].set_color('none')
35+
ax.spines['top'].set_color('none')
36+
ax.xaxis.set_ticks_position('bottom')
37+
ax.set_xticks([0, 1])
38+
ax.set_xlim([-0.5, 1.5])
39+
ax.set_ylim([0, 110])
40+
ax.set_xticklabels(['CONFIRMED BY\nEXPERIMENT', 'REFUTED BY\nEXPERIMENT'])
41+
plt.yticks([])
42+
43+
plt.title("CLAIMS OF SUPERNATURAL POWERS")
4544

4645
plt.show()

lib/matplotlib/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1050,12 +1050,15 @@ class rc_context(object):
10501050
def __init__(self, rc=None, fname=None):
10511051
self.rcdict = rc
10521052
self.fname = fname
1053-
def __enter__(self):
10541053
self._rcparams = rcParams.copy()
10551054
if self.fname:
10561055
rc_file(self.fname)
10571056
if self.rcdict:
10581057
rcParams.update(self.rcdict)
1058+
1059+
def __enter__(self):
1060+
return self
1061+
10591062
def __exit__(self, type, value, tb):
10601063
rcParams.update(self._rcparams)
10611064

lib/matplotlib/pyplot.py

Lines changed: 39 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -255,37 +255,53 @@ def setp(*args, **kwargs):
255255
draw_if_interactive()
256256
return ret
257257

258+
258259
def xkcd():
259260
"""
260-
Turns on `xkcd <xkcd.com>`_ sketch-style drawing mode. This will
261-
only have effect on things drawn after this function is called.
261+
Turns on `xkcd <http://xkcd.com/>`_ sketch-style drawing mode.
262+
This will only have effect on things drawn after this function is
263+
called.
262264
263265
For best results, the "Humor Sans" font should be installed: it is
264266
not included with matplotlib.
265267
266-
This function works by setting a whole slew of rcParams, so it will
267-
probably override others you have set before.
268+
This function works by a number of rcParams, so it will probably
269+
override others you have set before.
270+
271+
If you want the effects of this function to be temporary, it can
272+
be used as a context manager, for example::
273+
274+
with plt.xkcd():
275+
# This figure will be in XKCD-style
276+
fig1 = plt.figure()
277+
# ...
278+
279+
# This figure will be in regular style
280+
fig2 = plt.figure()
268281
"""
269282
from matplotlib import patheffects
270-
rcParams['text.usetex'] = False
271-
rcParams['font.family'] = 'fantasy'
272-
rcParams['font.fantasy'] = ['Humor Sans', 'Comic Sans MS']
273-
rcParams['font.size'] = 14.0
274-
rcParams['path.sketch'] = (1, 100, 2)
275-
rcParams['path.effects'] = [
276-
patheffects.withStroke(linewidth=4, foreground="w")]
277-
rcParams['axes.linewidth'] = 1.5
278-
rcParams['lines.linewidth'] = 2.0
279-
rcParams['figure.facecolor'] = 'white'
280-
rcParams['grid.linewidth'] = 0.0
281-
rcParams['axes.unicode_minus'] = False
282-
rcParams['axes.color_cycle'] = ['b', 'r', 'c', 'm']
283-
# rcParams['axes.clip'] = False
284-
rcParams['xtick.major.size'] = 8
285-
rcParams['xtick.major.width'] = 3
286-
rcParams['ytick.major.size'] = 8
287-
rcParams['ytick.major.width'] = 3
288-
283+
context = rc_context()
284+
try:
285+
rcParams['text.usetex'] = False
286+
rcParams['font.family'] = 'Humor Sans'
287+
rcParams['font.size'] = 14.0
288+
rcParams['path.sketch'] = (1, 100, 2)
289+
rcParams['path.effects'] = [
290+
patheffects.withStroke(linewidth=4, foreground="w")]
291+
rcParams['axes.linewidth'] = 1.5
292+
rcParams['lines.linewidth'] = 2.0
293+
rcParams['figure.facecolor'] = 'white'
294+
rcParams['grid.linewidth'] = 0.0
295+
rcParams['axes.unicode_minus'] = False
296+
rcParams['axes.color_cycle'] = ['b', 'r', 'c', 'm']
297+
rcParams['xtick.major.size'] = 8
298+
rcParams['xtick.major.width'] = 3
299+
rcParams['ytick.major.size'] = 8
300+
rcParams['ytick.major.width'] = 3
301+
except:
302+
context.__exit__(*sys.exc_info())
303+
raise
304+
return context
289305

290306
## Figures ##
291307

0 commit comments

Comments
 (0)