Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 1e1429a

Browse filesBrowse files
committed
Various examples updates.
- don't import out of pyplot or numpy, import as plt/np. - move some examples to use subplots() instead of add_subplot. - set random seed for some examples. - fix some docstrings.
1 parent 4872b79 commit 1e1429a
Copy full SHA for 1e1429a
Expand file treeCollapse file tree

39 files changed

+205
-241
lines changed

‎examples/axes_grid1/demo_colorbar_with_axes_divider.py

Copy file name to clipboardExpand all lines: examples/axes_grid1/demo_colorbar_with_axes_divider.py
+3-7Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,23 @@
44
===============================
55
66
"""
7+
78
import matplotlib.pyplot as plt
89
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
9-
1010
from mpl_toolkits.axes_grid1.colorbar import colorbar
11-
# from matplotlib.pyplot import colorbar
1211

13-
fig = plt.figure(1, figsize=(6, 3))
12+
fig, (ax1, ax2) = plt.subplots(1, 2)
1413
fig.subplots_adjust(wspace=0.5)
1514

16-
ax1 = fig.add_subplot(121)
1715
im1 = ax1.imshow([[1, 2], [3, 4]])
18-
1916
ax1_divider = make_axes_locatable(ax1)
2017
cax1 = ax1_divider.append_axes("right", size="7%", pad="2%")
2118
cb1 = colorbar(im1, cax=cax1)
2219

23-
ax2 = fig.add_subplot(122)
2420
im2 = ax2.imshow([[1, 2], [3, 4]])
25-
2621
ax2_divider = make_axes_locatable(ax2)
2722
cax2 = ax2_divider.append_axes("top", size="7%", pad="2%")
2823
cb2 = colorbar(im2, cax=cax2, orientation="horizontal")
2924
cax2.xaxis.set_ticks_position("top")
25+
3026
plt.show()

‎examples/event_handling/lasso_demo.py

Copy file name to clipboardExpand all lines: examples/event_handling/lasso_demo.py
+8-7Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,11 @@
1010
This is currently a proof-of-concept implementation (though it is
1111
usable as is). There will be some refinement of the API.
1212
"""
13-
from matplotlib.widgets import Lasso
14-
from matplotlib.collections import RegularPolyCollection
15-
from matplotlib import colors as mcolors, path
1613

17-
import matplotlib.pyplot as plt
18-
from numpy import nonzero
19-
from numpy.random import rand
14+
from matplotlib import colors as mcolors, path, pyplot as plt
15+
from matplotlib.collections import RegularPolyCollection
16+
from matplotlib.widgets import Lasso
17+
import numpy as np
2018

2119

2220
class Datum(object):
@@ -77,9 +75,12 @@ def onpress(self, event):
7775
# acquire a lock on the widget drawing
7876
self.canvas.widgetlock(self.lasso)
7977

78+
8079
if __name__ == '__main__':
8180

82-
data = [Datum(*xy) for xy in rand(100, 2)]
81+
np.random.seed(19680801)
82+
83+
data = [Datum(*xy) for xy in np.random.rand(100, 2)]
8384
ax = plt.axes(xlim=(0, 1), ylim=(0, 1), autoscale_on=False)
8485
ax.set_title('Lasso points using left mouse button')
8586

‎examples/event_handling/pick_event_demo2.py

Copy file name to clipboardExpand all lines: examples/event_handling/pick_event_demo2.py
+3-4Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,10 @@ def onpick(event):
2929
if not N:
3030
return True
3131

32-
figi = plt.figure()
33-
for subplotnum, dataind in enumerate(event.ind):
34-
ax = figi.add_subplot(N, 1, subplotnum + 1)
32+
figi, axs = plt.subplots(N, squeeze=False)
33+
for ax, dataind in zip(axs.flat, event.ind):
3534
ax.plot(X[dataind])
36-
ax.text(0.05, 0.9, 'mu=%1.3f\nsigma=%1.3f' % (xs[dataind], ys[dataind]),
35+
ax.text(.05, .9, 'mu=%1.3f\nsigma=%1.3f' % (xs[dataind], ys[dataind]),
3736
transform=ax.transAxes, va='top')
3837
ax.set_ylim(-0.5, 1.5)
3938
figi.show()

‎examples/event_handling/zoom_window.py

Copy file name to clipboardExpand all lines: examples/event_handling/zoom_window.py
+16-16Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,27 +6,27 @@
66
This example shows how to connect events in one window, for example, a mouse
77
press, to another figure window.
88
9-
If you click on a point in the first window, the z and y limits of the
10-
second will be adjusted so that the center of the zoom in the second
11-
window will be the x,y coordinates of the clicked point.
9+
If you click on a point in the first window, the z and y limits of the second
10+
will be adjusted so that the center of the zoom in the second window will be
11+
the x,y coordinates of the clicked point.
1212
13-
Note the diameter of the circles in the scatter are defined in
14-
points**2, so their size is independent of the zoom
13+
Note the diameter of the circles in the scatter are defined in points**2, so
14+
their size is independent of the zoom.
1515
"""
16-
from matplotlib.pyplot import figure, show
16+
17+
from matplotlib import pyplot as plt
1718
import numpy as np
18-
figsrc = figure()
19-
figzoom = figure()
20-
21-
axsrc = figsrc.add_subplot(111, xlim=(0, 1), ylim=(0, 1), autoscale_on=False)
22-
axzoom = figzoom.add_subplot(111, xlim=(0.45, 0.55), ylim=(0.4, .6),
23-
autoscale_on=False)
24-
axsrc.set_title('Click to zoom')
25-
axzoom.set_title('zoom window')
19+
20+
figsrc, axsrc = plt.subplots()
21+
figzoom, axzoom = plt.subplots()
22+
axsrc.set(xlim=(0, 1), ylim=(0, 1), autoscale_on=False,
23+
title='Click to zoom')
24+
axzoom.set(xlim=(0.45, 0.55), ylim=(0.4, 0.6), autoscale_on=False,
25+
title='Zoom window')
26+
2627
x, y, s, c = np.random.rand(4, 200)
2728
s *= 200
2829

29-
3030
axsrc.scatter(x, y, s, c)
3131
axzoom.scatter(x, y, s, c)
3232

@@ -40,4 +40,4 @@ def onpress(event):
4040
figzoom.canvas.draw()
4141

4242
figsrc.canvas.mpl_connect('button_press_event', onpress)
43-
show()
43+
plt.show()

‎examples/lines_bars_and_markers/eventplot_demo.py

Copy file name to clipboardExpand all lines: examples/lines_bars_and_markers/eventplot_demo.py
+9-14Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -32,18 +32,15 @@
3232
lineoffsets1 = np.array([-15, -3, 1, 1.5, 6, 10])
3333
linelengths1 = [5, 2, 1, 1, 3, 1.5]
3434

35-
fig = plt.figure()
35+
fig, axs = plt.subplots(2, 2)
3636

3737
# create a horizontal plot
38-
ax1 = fig.add_subplot(221)
39-
ax1.eventplot(data1, colors=colors1, lineoffsets=lineoffsets1,
40-
linelengths=linelengths1)
41-
38+
axs[0, 0].eventplot(data1, colors=colors1, lineoffsets=lineoffsets1,
39+
linelengths=linelengths1)
4240

4341
# create a vertical plot
44-
ax2 = fig.add_subplot(223)
45-
ax2.eventplot(data1, colors=colors1, lineoffsets=lineoffsets1,
46-
linelengths=linelengths1, orientation='vertical')
42+
axs[1, 0].eventplot(data1, colors=colors1, lineoffsets=lineoffsets1,
43+
linelengths=linelengths1, orientation='vertical')
4744

4845
# create another set of random data.
4946
# the gamma distribution is only used fo aesthetic purposes
@@ -57,14 +54,12 @@
5754
linelengths2 = 1
5855

5956
# create a horizontal plot
60-
ax1 = fig.add_subplot(222)
61-
ax1.eventplot(data2, colors=colors2, lineoffsets=lineoffsets2,
62-
linelengths=linelengths2)
57+
axs[0, 1].eventplot(data2, colors=colors2, lineoffsets=lineoffsets2,
58+
linelengths=linelengths2)
6359

6460

6561
# create a vertical plot
66-
ax2 = fig.add_subplot(224)
67-
ax2.eventplot(data2, colors=colors2, lineoffsets=lineoffsets2,
68-
linelengths=linelengths2, orientation='vertical')
62+
axs[1, 1].eventplot(data2, colors=colors2, lineoffsets=lineoffsets2,
63+
linelengths=linelengths2, orientation='vertical')
6964

7065
plt.show()

‎examples/lines_bars_and_markers/gradient_bar.py

Copy file name to clipboardExpand all lines: examples/lines_bars_and_markers/gradient_bar.py
+9-9Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@
55
66
"""
77
import matplotlib.pyplot as plt
8-
from numpy import arange
9-
from numpy.random import rand
8+
import numpy as np
9+
10+
np.random.seed(19680801)
1011

1112

1213
def gbar(ax, x, y, width=0.5, bottom=0):
@@ -17,20 +18,19 @@ def gbar(ax, x, y, width=0.5, bottom=0):
1718
extent=(left, right, bottom, top), alpha=1)
1819

1920

20-
fig = plt.figure()
21-
2221
xmin, xmax = xlim = 0, 10
2322
ymin, ymax = ylim = 0, 1
24-
ax = fig.add_subplot(111, xlim=xlim, ylim=ylim,
25-
autoscale_on=False)
26-
X = [[.6, .6], [.7, .7]]
2723

24+
fig, ax = plt.subplots()
25+
ax.set(xlim=xlim, ylim=ylim, autoscale_on=False)
26+
27+
X = [[.6, .6], [.7, .7]]
2828
ax.imshow(X, interpolation='bicubic', cmap=plt.cm.copper,
2929
extent=(xmin, xmax, ymin, ymax), alpha=1)
3030

3131
N = 10
32-
x = arange(N) + 0.25
33-
y = rand(N)
32+
x = np.arange(N) + 0.25
33+
y = np.random.rand(N)
3434
gbar(ax, x, y, width=0.7)
3535
ax.set_aspect('auto')
3636
plt.show()

‎examples/lines_bars_and_markers/interp_demo.py

Copy file name to clipboardExpand all lines: examples/lines_bars_and_markers/interp_demo.py
+4-4Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@
55
66
"""
77
import matplotlib.pyplot as plt
8-
from numpy import pi, sin, linspace
8+
import numpy as np
99
from matplotlib.mlab import stineman_interp
1010

11-
x = linspace(0, 2*pi, 20)
12-
y = sin(x)
11+
x = np.linspace(0, 2*np.pi, 20)
12+
y = np.sin(x)
1313
yp = None
14-
xi = linspace(x[0], x[-1], 100)
14+
xi = np.linspace(x[0], x[-1], 100)
1515
yi = stineman_interp(xi, x, y, yp)
1616

1717
fig, ax = plt.subplots()

‎examples/lines_bars_and_markers/simple_plot.py

Copy file name to clipboardExpand all lines: examples/lines_bars_and_markers/simple_plot.py
+2-1Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
66
Create a simple plot.
77
"""
8+
89
import matplotlib.pyplot as plt
910
import numpy as np
1011

@@ -13,7 +14,7 @@
1314
s = 1 + np.sin(2 * np.pi * t)
1415

1516
# Note that using plt.subplots below is equivalent to using
16-
# fig = plt.figure and then ax = fig.add_subplot(111)
17+
# fig = plt.figure() and then ax = fig.add_subplot(111)
1718
fig, ax = plt.subplots()
1819
ax.plot(t, s)
1920

‎examples/misc/pythonic_matplotlib.py

Copy file name to clipboardExpand all lines: examples/misc/pythonic_matplotlib.py
+7-12Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
instances, managing the bounding boxes of the figure elements,
1515
creating and realizing GUI windows and embedding figures in them.
1616
17-
1817
If you are an application developer and want to embed matplotlib in
1918
your application, follow the lead of examples/embedding_in_wx.py,
2019
examples/embedding_in_gtk.py or examples/embedding_in_tk.py. In this
@@ -55,30 +54,26 @@
5554
a.set_yticks([])
5655
"""
5756

57+
from matplotlib import pyplot as plt
58+
import numpy as np
5859

59-
from matplotlib.pyplot import figure, show
60-
from numpy import arange, sin, pi
61-
62-
t = arange(0.0, 1.0, 0.01)
60+
t = np.arange(0.0, 1.0, 0.01)
6361

64-
fig = figure(1)
62+
fig, (ax1, ax2) = plt.subplots(2)
6563

66-
ax1 = fig.add_subplot(211)
67-
ax1.plot(t, sin(2*pi * t))
64+
ax1.plot(t, np.sin(2*np.pi * t))
6865
ax1.grid(True)
6966
ax1.set_ylim((-2, 2))
7067
ax1.set_ylabel('1 Hz')
7168
ax1.set_title('A sine wave or two')
7269

7370
ax1.xaxis.set_tick_params(labelcolor='r')
7471

75-
76-
ax2 = fig.add_subplot(212)
77-
ax2.plot(t, sin(2 * 2*pi * t))
72+
ax2.plot(t, np.sin(2 * 2*np.pi * t))
7873
ax2.grid(True)
7974
ax2.set_ylim((-2, 2))
8075
l = ax2.set_xlabel('Hi mom')
8176
l.set_color('g')
8277
l.set_fontsize('large')
8378

84-
show()
79+
plt.show()

‎examples/pie_and_polar_charts/polar_legend.py

Copy file name to clipboardExpand all lines: examples/pie_and_polar_charts/polar_legend.py
+7-6Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,17 @@
55
66
Demo of a legend on a polar-axis plot.
77
"""
8+
9+
from matplotlib import pyplot as plt
810
import numpy as np
9-
from matplotlib.pyplot import figure, show, rc
1011

1112
# radar green, solid grid lines
12-
rc('grid', color='#316931', linewidth=1, linestyle='-')
13-
rc('xtick', labelsize=15)
14-
rc('ytick', labelsize=15)
13+
plt.rc('grid', color='#316931', linewidth=1, linestyle='-')
14+
plt.rc('xtick', labelsize=15)
15+
plt.rc('ytick', labelsize=15)
1516

1617
# force square figure and square axes looks better for polar, IMO
17-
fig = figure(figsize=(8, 8))
18+
fig = plt.figure(figsize=(8, 8))
1819
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8],
1920
projection='polar', facecolor='#d5de9c')
2021

@@ -24,4 +25,4 @@
2425
ax.plot(0.5 * theta, r, color='blue', ls='--', lw=3, label='another line')
2526
ax.legend()
2627

27-
show()
28+
plt.show()

‎examples/pyplots/align_ylabels.py

Copy file name to clipboardExpand all lines: examples/pyplots/align_ylabels.py
+2-7Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,35 +9,30 @@
99

1010
box = dict(facecolor='yellow', pad=5, alpha=0.2)
1111

12-
fig = plt.figure()
12+
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
1313
fig.subplots_adjust(left=0.2, wspace=0.6)
1414

1515
# Fixing random state for reproducibility
1616
np.random.seed(19680801)
1717

18-
ax1 = fig.add_subplot(221)
1918
ax1.plot(2000*np.random.rand(10))
2019
ax1.set_title('ylabels not aligned')
2120
ax1.set_ylabel('misaligned 1', bbox=box)
2221
ax1.set_ylim(0, 2000)
23-
ax3 = fig.add_subplot(223)
22+
2423
ax3.set_ylabel('misaligned 2',bbox=box)
2524
ax3.plot(np.random.rand(10))
2625

27-
2826
labelx = -0.3 # axes coords
2927

30-
ax2 = fig.add_subplot(222)
3128
ax2.set_title('ylabels aligned')
3229
ax2.plot(2000*np.random.rand(10))
3330
ax2.set_ylabel('aligned 1', bbox=box)
3431
ax2.yaxis.set_label_coords(labelx, 0.5)
3532
ax2.set_ylim(0, 2000)
3633

37-
ax4 = fig.add_subplot(224)
3834
ax4.plot(np.random.rand(10))
3935
ax4.set_ylabel('aligned 2', bbox=box)
4036
ax4.yaxis.set_label_coords(labelx, 0.5)
4137

42-
4338
plt.show()

‎examples/pyplots/dollar_ticks.py

Copy file name to clipboardExpand all lines: examples/pyplots/dollar_ticks.py
+1-2Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
# Fixing random state for reproducibility
1212
np.random.seed(19680801)
1313

14-
fig = plt.figure()
15-
ax = fig.add_subplot(111)
14+
fig, ax = plt.subplots()
1615
ax.plot(100*np.random.rand(20))
1716

1817
formatter = ticker.FormatStrFormatter('$%1.2f')

‎examples/recipes/common_date_problems.py

Copy file name to clipboardExpand all lines: examples/recipes/common_date_problems.py
+5-3Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,9 @@
5555

5656
# Matplotlib prefers datetime instead of np.datetime64.
5757
date = r.date.astype('O')
58-
plt.figure()
59-
plt.plot(date, r.close)
60-
plt.title('Default date handling can cause overlapping labels')
58+
fig, ax = plt.subplots()
59+
ax.plot(date, r.close)
60+
ax.set_title('Default date handling can cause overlapping labels')
6161

6262
###############################################################################
6363
# Another annoyance is that if you hover the mouse over the window and
@@ -88,3 +88,5 @@
8888
###############################################################################
8989
# Now when you hover your mouse over the plotted data, you'll see date
9090
# format strings like 2004-12-01 in the toolbar.
91+
92+
plt.show()

‎examples/recipes/create_subplots.py

Copy file name to clipboardExpand all lines: examples/recipes/create_subplots.py
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,5 @@
3737
# new style method 2; use an axes array
3838
fig, axs = plt.subplots(2, 2, sharex=True, sharey=True)
3939
axs[0, 0].plot(x)
40+
41+
plt.show()

‎examples/recipes/fill_between_alpha.py

Copy file name to clipboardExpand all lines: examples/recipes/fill_between_alpha.py
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,3 +134,5 @@
134134
# functions :meth:`~matplotlib.axes.Axes.axhspan` and
135135
# :meth:`~matplotlib.axes.Axes.axvspan` and example
136136
# :ref:`sphx_glr_gallery_subplots_axes_and_figures_axhspan_demo.py`.
137+
138+
plt.show()

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.