Skip to content

Commit 5bb185e

Browse files
ivanovmdboom
authored andcommitted
use plt.subplots() in examples as much as possible
At the recent LBL Software Carpentry Workshop, it was pointed out that there's an inconsistency within our documentation for how to create new figures with subplots. Indeed, most examples were using the old way, something like: fig = plt.figure() ax = plt.subplot(111) # or plt.add_subplot(111) This patch changes a whole bunch of instances like the above to: fig, ax = plt.subplots() We should strive to have a minimal amount of constants in our code, especially unusual ones like `111`, which only make sense to Matlab refugees. I have left unchanged examples which were using axes keywords passed to subplot() and add_subplot(), since those end up transforming things like: figure() subplot(111, axisbg='w') to plt.subplots(subplot_kw=dict(axisbg='w')) which isn't necessarily better. I also did not touch most of the user_interfaces examples, since those did not involve using plt, but instead explicitly imported Figure, and used the OO approach on Figure instances. Also updated instaces where the old "import pylab as p" convention was used to use our standard "import matplotlib.pyplot as plt" I have also updated some, but not all uses of subplot(121) etc, but I'm a bit exhausted after doing all of these.
1 parent e783faa commit 5bb185e

File tree

121 files changed

+191
-330
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

121 files changed

+191
-330
lines changed

CHANGELOG

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,10 @@
9090

9191
2012-11-09 Make plt.subplot() without arguments act as subplot(111) - PI
9292

93+
2012-11-08 Replaced plt.figure and plt.subplot calls by the newer, more
94+
convenient single call to plt.subplots() in the documentation
95+
examples - PI
96+
9397
2012-10-05 Add support for saving animations as animated GIFs. - JVDP
9498

9599
2012-08-11 Fix path-closing bug in patches.Polygon, so that regardless

examples/animation/animate_decay.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@ def data_gen():
1111
yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)
1212
data_gen.t = 0
1313

14-
fig = plt.figure()
15-
ax = fig.add_subplot(111)
14+
fig, ax = plt.subplots()
1615
line, = ax.plot([], [], lw=2)
1716
ax.set_ylim(-1.1, 1.1)
1817
ax.set_xlim(0, 5)

examples/animation/histogram.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@
99
import matplotlib.path as path
1010
import matplotlib.animation as animation
1111

12-
fig = plt.figure()
13-
ax = fig.add_subplot(111)
12+
fig, ax = plt.subplots()
1413

1514
# histogram our data with numpy
1615
data = np.random.randn(1000)

examples/animation/old_animation/animate_decay_tk_blit.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@ def data_gen():
1010
return np.sin(2*np.pi*t) * np.exp(-t/10.)
1111
data_gen.t = 0
1212

13-
fig = plt.figure()
14-
ax = fig.add_subplot(111)
13+
fig, ax = plt.subplots()
1514
line, = ax.plot([], [], animated=True, lw=2)
1615
ax.set_ylim(-1.1, 1.1)
1716
ax.set_xlim(0, 5)

examples/animation/old_animation/animation_blit_gtk.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,7 @@
1616
import matplotlib.pyplot as plt
1717

1818

19-
fig = plt.figure()
20-
ax = fig.add_subplot(111)
19+
fig, ax = plt.subplots()
2120
canvas = fig.canvas
2221

2322
fig.subplots_adjust(left=0.3, bottom=0.3) # check for flipy bugs

examples/animation/old_animation/animation_blit_gtk2.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,9 +148,8 @@ def update_line(self, *args):
148148

149149

150150
plt.rcParams["text.usetex"] = False
151-
fig = plt.figure()
152151

153-
ax = fig.add_subplot(111)
152+
fig, ax = plt.subplots()
154153
ax.xaxis.set_animated(True)
155154
ax.yaxis.set_animated(True)
156155
canvas = fig.canvas

examples/animation/old_animation/animation_blit_tk.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,17 @@
77
matplotlib.use('TkAgg')
88

99
import sys
10-
import pylab as p
10+
import matplotlib.pyplot as plt
1111
import numpy as npy
1212
import time
1313

14-
ax = p.subplot(111)
14+
fig, ax = plt.subplots()
1515
canvas = ax.figure.canvas
1616

1717

1818
# create the initial line
1919
x = npy.arange(0,2*npy.pi,0.01)
20-
line, = p.plot(x, npy.sin(x), animated=True, lw=2)
20+
line, = plt.plot(x, npy.sin(x), animated=True, lw=2)
2121

2222
def run(*args):
2323
background = canvas.copy_from_bbox(ax.bbox)
@@ -43,12 +43,12 @@ def run(*args):
4343
run.cnt = 0
4444

4545

46-
p.subplots_adjust(left=0.3, bottom=0.3) # check for flipy bugs
47-
p.grid() # to ensure proper background restore
48-
manager = p.get_current_fig_manager()
46+
plt.subplots_adjust(left=0.3, bottom=0.3) # check for flipy bugs
47+
plt.grid() # to ensure proper background restore
48+
manager = plt.get_current_fig_manager()
4949
manager.window.after(100, run)
5050

51-
p.show()
51+
plt.show()
5252

5353

5454

examples/animation/old_animation/animation_blit_wx.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
matplotlib.backends.backend_wxagg._use_accelerator(False)
2525

2626

27-
ax = p.subplot(111)
27+
fig, ax = plt.subplots()
2828
canvas = ax.figure.canvas
2929

3030

examples/animation/old_animation/draggable_legend.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
import matplotlib.pyplot as plt
22

3-
4-
ax = plt.subplot(111)
3+
fig, ax = plt.subplots()
54
ax.plot([1,2,3], label="test")
65

76
l = ax.legend()
87
d1 = l.draggable()
98

10-
xy = 1, 2
9+
xy = 1, 2
1110
txt = ax.annotate("Test", xy, xytext=(-30, 30),
1211
textcoords="offset points",
1312
bbox=dict(boxstyle="round",fc=(0.2, 1, 1)),

examples/animation/old_animation/gtk_timeout.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@
55

66
import matplotlib.pyplot as plt
77

8-
fig = plt.figure()
9-
ax = fig.add_subplot(111)
8+
fig, ax = plt.subplots()
109
line, = ax.plot(np.random.rand(10))
1110
ax.set_ylim(0, 1)
1211

examples/animation/old_animation/histogram_tkagg.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
import matplotlib.patches as patches
1212
import matplotlib.path as path
1313

14-
fig = plt.figure()
15-
ax = fig.add_subplot(111)
14+
fig, ax = plt.subplots()
1615

1716
# histogram our data with numpy
1817
data = np.random.randn(1000)

examples/animation/old_animation/simple_anim_gtk.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,7 @@
99

1010
import matplotlib.pyplot as plt
1111

12-
fig = plt.figure()
13-
14-
ax = fig.add_subplot(111)
12+
fig, ax = plt.subplots()
1513

1614
def animate():
1715
tstart = time.time() # for profiling

examples/animation/old_animation/simple_anim_tkagg.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@
1010
matplotlib.use('TkAgg') # do this before importing pylab
1111

1212
import matplotlib.pyplot as plt
13-
fig = plt.figure()
14-
ax = fig.add_subplot(111)
13+
fig, ax = plt.subplots()
1514

1615
def animate():
1716
tstart = time.time() # for profiling

examples/animation/old_animation/simple_idle_wx.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,7 @@
99

1010
import matplotlib.pyplot as plt
1111

12-
fig = plt.figure()
13-
14-
ax = fig.add_subplot(111)
12+
fig, ax = plt.subplots()
1513
t = np.arange(0, 2*np.pi, 0.1)
1614
line, = ax.plot(t, np.sin(t))
1715
dt = 0.05

examples/animation/old_animation/simple_timer_wx.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,7 @@
99

1010
import matplotlib.pyplot as plt
1111

12-
fig = plt.figure()
13-
14-
ax = fig.add_subplot(111)
12+
fig, ax = plt.subplots()
1513
t = np.arange(0, 2*np.pi, 0.1)
1614
line, = ax.plot(t, np.sin(t))
1715
dt = 0.05

examples/animation/old_animation/strip_chart_demo.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,7 @@ def update(self, *args):
6464

6565
from pylab import figure, show
6666

67-
fig = figure()
68-
ax = fig.add_subplot(111)
67+
fig, ax = plt.subplots()
6968
scope = Scope(ax)
7069
gobject.idle_add(scope.update)
7170

examples/animation/random_data.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,7 @@
22
import matplotlib.pyplot as plt
33
import matplotlib.animation as animation
44

5-
fig = plt.figure()
6-
ax = fig.add_subplot(111)
5+
fig, ax = plt.subplots()
76
line, = ax.plot(np.random.rand(10))
87
ax.set_ylim(0, 1)
98

examples/animation/simple_anim.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@
55
import matplotlib.pyplot as plt
66
import matplotlib.animation as animation
77

8-
fig = plt.figure()
9-
ax = fig.add_subplot(111)
8+
fig, ax = plt.subplots()
109

1110
x = np.arange(0, 2*np.pi, 0.01) # x-array
1211
line, = ax.plot(x, np.sin(x))

examples/animation/strip_chart_demo.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,7 @@ def emitter(p=0.03):
4444
else:
4545
yield np.random.rand(1)
4646

47-
fig = plt.figure()
48-
ax = fig.add_subplot(111)
47+
fig, ax = plt.subplots()
4948
scope = Scope(ax)
5049

5150
# pass a generator in "emitter" to produce data for the update func

examples/api/README.txt

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,7 @@ A simple example of the recommended style is::
2929
import numpy as np
3030
import matplotlib.pyplot as plt
3131

32-
fig = plt.figure()
33-
ax = fig.add_subplot(111) # or add_axes
32+
fig, ax = plt.subplots()
3433
ax.plot(np.random.rand(10))
3534
ax.set_xlabel('some x data')
3635
ax.set_ylabel('some y data')

examples/api/agg_oo.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,10 @@
66
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
77
from matplotlib.figure import Figure
88

9-
fig = Figure()
10-
canvas = FigureCanvas(fig)
11-
ax = fig.add_subplot(111)
9+
fig, ax = plt.subplots()
1210
ax.plot([1,2,3])
1311
ax.set_title('hi mom')
1412
ax.grid(True)
1513
ax.set_xlabel('time')
1614
ax.set_ylabel('volts')
17-
canvas.print_figure('test')
15+
fig.canvas.print_figure('test')

examples/api/barchart_demo.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
ind = np.arange(N) # the x locations for the groups
1212
width = 0.35 # the width of the bars
1313

14-
fig = plt.figure()
15-
ax = fig.add_subplot(111)
14+
fig, ax = plt.subplots()
1615
rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd)
1716

1817
womenMeans = (25, 32, 34, 20, 25)

examples/api/collections_demo.py

Lines changed: 22 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -41,69 +41,63 @@
4141
# Make a list of colors cycling through the rgbcmyk series.
4242
colors = [colorConverter.to_rgba(c) for c in ('r','g','b','c','y','m','k')]
4343

44-
fig = plt.figure()
44+
fig, axes = plt.subplots(2,2)
45+
((ax1, ax2), (ax3, ax4)) = axes # unpack the axes
46+
4547

46-
a = fig.add_subplot(2,2,1)
4748
col = collections.LineCollection([spiral], offsets=xyo,
48-
transOffset=a.transData)
49+
transOffset=ax1.transData)
4950
trans = fig.dpi_scale_trans + transforms.Affine2D().scale(1.0/72.0)
5051
col.set_transform(trans) # the points to pixels transform
5152
# Note: the first argument to the collection initializer
5253
# must be a list of sequences of x,y tuples; we have only
5354
# one sequence, but we still have to put it in a list.
54-
a.add_collection(col, autolim=True)
55+
ax1.add_collection(col, autolim=True)
5556
# autolim=True enables autoscaling. For collections with
5657
# offsets like this, it is neither efficient nor accurate,
5758
# but it is good enough to generate a plot that you can use
5859
# as a starting point. If you know beforehand the range of
5960
# x and y that you want to show, it is better to set them
6061
# explicitly, leave out the autolim kwarg (or set it to False),
61-
# and omit the 'a.autoscale_view()' call below.
62+
# and omit the 'ax1.autoscale_view()' call below.
6263

6364
# Make a transform for the line segments such that their size is
6465
# given in points:
6566
col.set_color(colors)
6667

67-
a.autoscale_view() # See comment above, after a.add_collection.
68-
a.set_title('LineCollection using offsets')
68+
ax1.autoscale_view() # See comment above, after ax1.add_collection.
69+
ax1.set_title('LineCollection using offsets')
6970

7071

7172
# The same data as above, but fill the curves.
72-
73-
a = fig.add_subplot(2,2,2)
74-
7573
col = collections.PolyCollection([spiral], offsets=xyo,
76-
transOffset=a.transData)
74+
transOffset=ax2.transData)
7775
trans = transforms.Affine2D().scale(fig.dpi/72.0)
7876
col.set_transform(trans) # the points to pixels transform
79-
a.add_collection(col, autolim=True)
77+
ax2.add_collection(col, autolim=True)
8078
col.set_color(colors)
8179

8280

83-
a.autoscale_view()
84-
a.set_title('PolyCollection using offsets')
81+
ax2.autoscale_view()
82+
ax2.set_title('PolyCollection using offsets')
8583

8684
# 7-sided regular polygons
8785

88-
a = fig.add_subplot(2,2,3)
89-
9086
col = collections.RegularPolyCollection(7,
9187
sizes = np.fabs(xx)*10.0, offsets=xyo,
92-
transOffset=a.transData)
88+
transOffset=ax3.transData)
9389
trans = transforms.Affine2D().scale(fig.dpi/72.0)
9490
col.set_transform(trans) # the points to pixels transform
95-
a.add_collection(col, autolim=True)
91+
ax3.add_collection(col, autolim=True)
9692
col.set_color(colors)
97-
a.autoscale_view()
98-
a.set_title('RegularPolyCollection using offsets')
93+
ax3.autoscale_view()
94+
ax3.set_title('RegularPolyCollection using offsets')
9995

10096

10197
# Simulate a series of ocean current profiles, successively
10298
# offset by 0.1 m/s so that they form what is sometimes called
10399
# a "waterfall" plot or a "stagger" plot.
104100

105-
a = fig.add_subplot(2,2,4)
106-
107101
nverts = 60
108102
ncurves = 20
109103
offs = (0.1, 0.0)
@@ -118,14 +112,14 @@
118112
segs.append(curve)
119113

120114
col = collections.LineCollection(segs, offsets=offs)
121-
a.add_collection(col, autolim=True)
115+
ax4.add_collection(col, autolim=True)
122116
col.set_color(colors)
123-
a.autoscale_view()
124-
a.set_title('Successive data offsets')
125-
a.set_xlabel('Zonal velocity component (m/s)')
126-
a.set_ylabel('Depth (m)')
117+
ax4.autoscale_view()
118+
ax4.set_title('Successive data offsets')
119+
ax4.set_xlabel('Zonal velocity component (m/s)')
120+
ax4.set_ylabel('Depth (m)')
127121
# Reverse the y-axis so depth increases downward
128-
a.set_ylim(a.get_ylim()[::-1])
122+
ax4.set_ylim(ax4.get_ylim()[::-1])
129123

130124

131125
plt.show()

examples/api/compound_path.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,7 @@
2323

2424
pathpatch = PathPatch(path, facecolor='None', edgecolor='green')
2525

26-
fig = plt.figure()
27-
ax = fig.add_subplot(111)
26+
fig, ax = plt.subplots()
2827
ax.add_patch(pathpatch)
2928
ax.set_title('A compound path')
3029

examples/api/date_demo.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,7 @@
2828
datafile = cbook.get_sample_data('goog.npy')
2929
r = np.load(datafile).view(np.recarray)
3030

31-
fig = plt.figure()
32-
ax = fig.add_subplot(111)
31+
fig, ax = plt.subplots()
3332
ax.plot(r.date, r.adj_close)
3433

3534

0 commit comments

Comments
 (0)