Skip to content

Commit d72e92f

Browse files
committed
Clean up imports in examples.
Remove pylab imports (except examples in pylab_examples and animation/old_animation) and replace them with: import matplotlib.pyplot as plt import numpy as np
1 parent 396a644 commit d72e92f

24 files changed

+210
-211
lines changed

examples/api/bbox_intersect.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,19 @@
1-
from pylab import *
21
import numpy as np
2+
import matplotlib.pyplot as plt
33
from matplotlib.transforms import Bbox
44
from matplotlib.path import Path
5-
from matplotlib.patches import Rectangle
65

7-
rect = Rectangle((-1, -1), 2, 2, facecolor="#aaaaaa")
8-
gca().add_patch(rect)
6+
rect = plt.Rectangle((-1, -1), 2, 2, facecolor="#aaaaaa")
7+
plt.gca().add_patch(rect)
98
bbox = Bbox.from_bounds(-1, -1, 2, 2)
109

1110
for i in range(12):
12-
vertices = (np.random.random((4, 2)) - 0.5) * 6.0
13-
vertices = np.ma.masked_array(vertices, [[False, False], [True, True], [False, False], [False, False]])
11+
vertices = (np.random.random((2, 2)) - 0.5) * 6.0
1412
path = Path(vertices)
1513
if path.intersects_bbox(bbox):
1614
color = 'r'
1715
else:
1816
color = 'b'
19-
plot(vertices[:,0], vertices[:,1], color=color)
17+
plt.plot(vertices[:,0], vertices[:,1], color=color)
2018

21-
show()
19+
plt.show()

examples/api/collections_demo.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,31 +17,31 @@
1717
1818
'''
1919

20-
import matplotlib.pyplot as P
21-
from matplotlib import collections, axes, transforms
20+
import matplotlib.pyplot as plt
21+
from matplotlib import collections, transforms
2222
from matplotlib.colors import colorConverter
23-
import numpy as N
23+
import numpy as np
2424

2525
nverts = 50
2626
npts = 100
2727

2828
# Make some spirals
29-
r = N.array(range(nverts))
30-
theta = N.array(range(nverts)) * (2*N.pi)/(nverts-1)
31-
xx = r * N.sin(theta)
32-
yy = r * N.cos(theta)
29+
r = np.array(range(nverts))
30+
theta = np.array(range(nverts)) * (2*np.pi)/(nverts-1)
31+
xx = r * np.sin(theta)
32+
yy = r * np.cos(theta)
3333
spiral = list(zip(xx,yy))
3434

3535
# Make some offsets
36-
rs = N.random.RandomState([12345678])
36+
rs = np.random.RandomState([12345678])
3737
xo = rs.randn(npts)
3838
yo = rs.randn(npts)
3939
xyo = list(zip(xo, yo))
4040

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 = P.figure()
44+
fig = plt.figure()
4545

4646
a = fig.add_subplot(2,2,1)
4747
col = collections.LineCollection([spiral], offsets=xyo,
@@ -88,7 +88,7 @@
8888
a = fig.add_subplot(2,2,3)
8989

9090
col = collections.RegularPolyCollection(7,
91-
sizes = N.fabs(xx)*10.0, offsets=xyo,
91+
sizes = np.fabs(xx)*10.0, offsets=xyo,
9292
transOffset=a.transData)
9393
trans = transforms.Affine2D().scale(fig.dpi/72.0)
9494
col.set_transform(trans) # the points to pixels transform
@@ -108,9 +108,9 @@
108108
ncurves = 20
109109
offs = (0.1, 0.0)
110110

111-
yy = N.linspace(0, 2*N.pi, nverts)
112-
ym = N.amax(yy)
113-
xx = (0.2 + (ym-yy)/ym)**2 * N.cos(yy-0.4) * 0.5
111+
yy = np.linspace(0, 2*np.pi, nverts)
112+
ym = np.amax(yy)
113+
xx = (0.2 + (ym-yy)/ym)**2 * np.cos(yy-0.4) * 0.5
114114
segs = []
115115
for i in range(ncurves):
116116
xxx = xx + 0.02*rs.randn(nverts)
@@ -128,6 +128,6 @@
128128
a.set_ylim(a.get_ylim()[::-1])
129129

130130

131-
P.show()
131+
plt.show()
132132

133133

examples/api/custom_projection_example.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
from __future__ import unicode_literals
2+
3+
import matplotlib.pyplot as plt
24
from matplotlib.axes import Axes
3-
from matplotlib import cbook
45
from matplotlib.patches import Circle
56
from matplotlib.path import Path
6-
from matplotlib.ticker import Formatter, Locator, NullLocator, FixedLocator, NullFormatter
7-
from matplotlib.transforms import Affine2D, Affine2DBase, Bbox, \
8-
BboxTransformTo, IdentityTransform, Transform, TransformWrapper
7+
from matplotlib.transforms import Affine2D, BboxTransformTo, Transform
98
from matplotlib.projections import register_projection
109
import matplotlib.spines as mspines
1110
import matplotlib.axis as maxis
@@ -56,8 +55,8 @@ def cla(self):
5655
self.set_longitude_grid_ends(75)
5756

5857
# Turn off minor ticking altogether
59-
self.xaxis.set_minor_locator(NullLocator())
60-
self.yaxis.set_minor_locator(NullLocator())
58+
self.xaxis.set_minor_locator(plt.NullLocator())
59+
self.yaxis.set_minor_locator(plt.NullLocator())
6160

6261
# Do not display ticks -- we only want gridlines and text
6362
self.xaxis.set_ticks_position('none')
@@ -283,7 +282,7 @@ def format_coord(self, long, lat):
283282
# \u00b0 : degree symbol
284283
return '%f\u00b0%s, %f\u00b0%s' % (abs(lat), ns, abs(long), ew)
285284

286-
class DegreeFormatter(Formatter):
285+
class DegreeFormatter(plt.Formatter):
287286
"""
288287
This is a custom formatter that converts the native unit of
289288
radians into (truncated) degrees and adds a degree symbol.
@@ -309,7 +308,7 @@ class -- it provides a more convenient interface to set the
309308
# by degrees.
310309
number = (360.0 / degrees) + 1
311310
self.xaxis.set_major_locator(
312-
FixedLocator(
311+
plt.FixedLocator(
313312
np.linspace(-np.pi, np.pi, number, True)[1:-1]))
314313
# Set the formatter to display the tick labels in degrees,
315314
# rather than radians.
@@ -327,7 +326,7 @@ class -- it provides a more convenient interface than
327326
# by degrees.
328327
number = (180.0 / degrees) + 1
329328
self.yaxis.set_major_locator(
330-
FixedLocator(
329+
plt.FixedLocator(
331330
np.linspace(-np.pi / 2.0, np.pi / 2.0, number, True)[1:-1]))
332331
# Set the formatter to display the tick labels in degrees,
333332
# rather than radians.
@@ -448,10 +447,9 @@ def inverted(self):
448447
register_projection(HammerAxes)
449448

450449
# Now make a simple example using the custom projection.
451-
from pylab import *
450+
plt.subplot(111, projection="custom_hammer")
451+
p = plt.plot([-1, 1, 1], [-1, -1, 1], "o-")
452+
plt.grid(True)
452453

453-
subplot(111, projection="custom_hammer")
454-
p = plot([-1, 1, 1], [-1, -1, 1], "o-")
455-
grid(True)
454+
plt.show()
456455

457-
show()

examples/api/custom_scale_example.py

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
from __future__ import unicode_literals
2+
3+
import numpy as np
4+
from numpy import ma
5+
import matplotlib.pyplot as plt
26
from matplotlib import scale as mscale
37
from matplotlib import transforms as mtransforms
48

9+
510
class MercatorLatitudeScale(mscale.ScaleBase):
611
"""
712
Scales data in range -pi/2 to pi/2 (-90 to 90 degrees) using
@@ -65,13 +70,13 @@ def set_default_locators_and_formatters(self, axis):
6570
the radians to degrees and put a degree symbol after the
6671
value::
6772
"""
68-
class DegreeFormatter(Formatter):
73+
class DegreeFormatter(plt.Formatter):
6974
def __call__(self, x, pos=None):
7075
# \u00b0 : degree symbol
7176
return "%d\u00b0" % ((x / np.pi) * 180.0)
7277

7378
deg2rad = np.pi / 180.0
74-
axis.set_major_locator(FixedLocator(
79+
axis.set_major_locator(plt.FixedLocator(
7580
np.arange(-90, 90, 10) * deg2rad))
7681
axis.set_major_formatter(DegreeFormatter())
7782
axis.set_minor_formatter(DegreeFormatter())
@@ -149,18 +154,16 @@ def inverted(self):
149154
# that ``matplotlib`` can find it.
150155
mscale.register_scale(MercatorLatitudeScale)
151156

152-
from pylab import *
153-
import numpy as np
154-
155-
t = arange(-180.0, 180.0, 0.1)
157+
t = np.arange(-180.0, 180.0, 0.1)
156158
s = t / 360.0 * np.pi
157159

158-
plot(t, s, '-', lw=2)
159-
gca().set_yscale('mercator')
160+
plt.plot(t, s, '-', lw=2)
161+
plt.gca().set_yscale('mercator')
162+
163+
plt.xlabel('Longitude')
164+
plt.ylabel('Latitude')
165+
plt.title('Mercator: Projection of the Oppressor')
166+
plt.grid(True)
160167

161-
xlabel('Longitude')
162-
ylabel('Latitude')
163-
title('Mercator: Projection of the Oppressor')
164-
grid(True)
168+
plt.show()
165169

166-
show()

examples/api/logo2.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
import matplotlib as mpl
77
import matplotlib.pyplot as plt
88
import matplotlib.cm as cm
9-
import matplotlib.mlab as mlab
10-
from pylab import rand
119

1210
mpl.rcParams['xtick.labelsize'] = 10
1311
mpl.rcParams['ytick.labelsize'] = 12

examples/api/patch_collection.py

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,28 @@
1+
import numpy as np
12
import matplotlib
23
from matplotlib.patches import Circle, Wedge, Polygon
34
from matplotlib.collections import PatchCollection
4-
import pylab
5+
import matplotlib.pyplot as plt
56

6-
fig=pylab.figure()
7+
8+
fig=plt.figure()
79
ax=fig.add_subplot(111)
810

911
resolution = 50 # the number of vertices
1012
N = 3
11-
x = pylab.rand(N)
12-
y = pylab.rand(N)
13-
radii = 0.1*pylab.rand(N)
13+
x = np.random.rand(N)
14+
y = np.random.rand(N)
15+
radii = 0.1*np.random.rand(N)
1416
patches = []
1517
for x1,y1,r in zip(x, y, radii):
1618
circle = Circle((x1,y1), r)
1719
patches.append(circle)
1820

19-
x = pylab.rand(N)
20-
y = pylab.rand(N)
21-
radii = 0.1*pylab.rand(N)
22-
theta1 = 360.0*pylab.rand(N)
23-
theta2 = 360.0*pylab.rand(N)
21+
x = np.random.rand(N)
22+
y = np.random.rand(N)
23+
radii = 0.1*np.random.rand(N)
24+
theta1 = 360.0*np.random.rand(N)
25+
theta2 = 360.0*np.random.rand(N)
2426
for x1,y1,r,t1,t2 in zip(x, y, radii, theta1, theta2):
2527
wedge = Wedge((x1,y1), r, t1, t2)
2628
patches.append(wedge)
@@ -34,13 +36,13 @@
3436
]
3537

3638
for i in range(N):
37-
polygon = Polygon(pylab.rand(N,2), True)
39+
polygon = Polygon(np.random.rand(N,2), True)
3840
patches.append(polygon)
3941

40-
colors = 100*pylab.rand(len(patches))
42+
colors = 100*np.random.rand(len(patches))
4143
p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)
42-
p.set_array(pylab.array(colors))
44+
p.set_array(np.array(colors))
4345
ax.add_collection(p)
44-
pylab.colorbar(p)
46+
plt.colorbar(p)
4547

46-
pylab.show()
48+
plt.show()

examples/api/sankey_demo_old.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
__author__ = "Yannick Copin <ycopin@ipnl.in2p3.fr>"
66
__version__ = "Time-stamp: <10/02/2010 16:49 ycopin@lyopc548.in2p3.fr>"
77

8-
import numpy as N
8+
import numpy as np
99

1010
def sankey(ax,
1111
outputs=[100.], outlabels=None,
@@ -30,19 +30,19 @@ def sankey(ax,
3030
import matplotlib.patches as mpatches
3131
from matplotlib.path import Path
3232

33-
outs = N.absolute(outputs)
34-
outsigns = N.sign(outputs)
33+
outs = np.absolute(outputs)
34+
outsigns = np.sign(outputs)
3535
outsigns[-1] = 0 # Last output
3636

37-
ins = N.absolute(inputs)
38-
insigns = N.sign(inputs)
37+
ins = np.absolute(inputs)
38+
insigns = np.sign(inputs)
3939
insigns[0] = 0 # First input
4040

4141
assert sum(outs)==100, "Outputs don't sum up to 100%"
4242
assert sum(ins)==100, "Inputs don't sum up to 100%"
4343

4444
def add_output(path, loss, sign=1):
45-
h = (loss/2+w)*N.tan(outangle/180.*N.pi) # Arrow tip height
45+
h = (loss/2+w)*np.tan(outangle/180.*np.pi) # Arrow tip height
4646
move,(x,y) = path[-1] # Use last point as reference
4747
if sign==0: # Final loss (horizontal)
4848
path.extend([(Path.LINETO,[x+dx,y]),
@@ -64,7 +64,7 @@ def add_output(path, loss, sign=1):
6464
outtips.append((sign,path[-5][1]))
6565

6666
def add_input(path, gain, sign=1):
67-
h = (gain/2)*N.tan(inangle/180.*N.pi) # Dip depth
67+
h = (gain/2)*np.tan(inangle/180.*np.pi) # Dip depth
6868
move,(x,y) = path[-1] # Use last point as reference
6969
if sign==0: # First gain (horizontal)
7070
path.extend([(Path.LINETO,[x-dx,y]),
@@ -109,7 +109,7 @@ def revert(path):
109109
path = urpath + revert(lrpath) + llpath + revert(ulpath)
110110

111111
codes,verts = zip(*path)
112-
verts = N.array(verts)
112+
verts = np.array(verts)
113113

114114
# Path patch
115115
path = Path(verts,codes)

examples/event_handling/data_browser.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import numpy as np
2-
from pylab import figure, show
2+
import matplotlib.pyplot as plt
33

44

55
X = np.random.rand(100, 200)
66
xs = np.mean(X, axis=1)
77
ys = np.std(X, axis=1)
88

9-
fig = figure()
9+
fig = plt.figure()
1010
ax = fig.add_subplot(211)
1111
ax.set_title('click on point to plot time series')
1212
line, = ax.plot(xs, ys, 'o', picker=5) # 5 points tolerance
@@ -79,4 +79,4 @@ def update(self):
7979
fig.canvas.mpl_connect('pick_event', browser.onpick)
8080
fig.canvas.mpl_connect('key_press_event', browser.onpress)
8181

82-
show()
82+
plt.show()

examples/event_handling/keypress_demo.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
Show how to connect to keypress events
55
"""
66
from __future__ import print_function
7-
import numpy as n
8-
from pylab import figure, show
7+
import numpy as np
8+
import matplotlib.pyplot as plt
9+
910

1011
def press(event):
1112
print('press', event.key)
@@ -14,12 +15,12 @@ def press(event):
1415
xl.set_visible(not visible)
1516
fig.canvas.draw()
1617

17-
fig = figure()
18+
fig = plt.figure()
1819
ax = fig.add_subplot(111)
1920

2021
fig.canvas.mpl_connect('key_press_event', press)
2122

22-
ax.plot(n.random.rand(12), n.random.rand(12), 'go')
23+
ax.plot(np.random.rand(12), np.random.rand(12), 'go')
2324
xl = ax.set_xlabel('easy come, easy go')
2425

25-
show()
26+
plt.show()

0 commit comments

Comments
 (0)