Skip to content

Commit bf514e5

Browse 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 bf514e5

29 files changed

+154
-162
lines changed

examples/axes_grid1/demo_colorbar_with_axes_divider.py

+3-7
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

+8-7
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/zoom_window.py

+16-16
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/gradient_bar.py

+9-9
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

+4-4
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/misc/pythonic_matplotlib.py

+7-12
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

+7-6
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/recipes/common_date_problems.py

+5-3
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.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

+2
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

+2
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()

examples/recipes/placing_text_boxes.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import numpy as np
1414
import matplotlib.pyplot as plt
1515

16-
np.random.seed(1234)
16+
np.random.seed(19680801)
1717

1818
fig, ax = plt.subplots()
1919
x = 30*np.random.randn(10000)
@@ -29,3 +29,5 @@
2929
# place a text box in upper left in axes coords
3030
ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14,
3131
verticalalignment='top', bbox=props)
32+
33+
plt.show()

examples/recipes/share_axis_lims_views.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@
1717
t = np.arange(0, 10, 0.01)
1818

1919
ax1 = plt.subplot(211)
20-
2120
ax1.plot(t, np.sin(2*np.pi*t))
2221

2322
ax2 = plt.subplot(212, sharex=ax1)
24-
2523
ax2.plot(t, np.sin(4*np.pi*t))
24+
25+
plt.show()

examples/recipes/transparent_legends.py

+2
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,5 @@
2929

3030
ax.legend(loc='best', fancybox=True, framealpha=0.5)
3131
ax.set_title('fancy, transparent legends')
32+
33+
plt.show()

examples/subplots_axes_and_figures/custom_figure_class.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
You can pass a custom Figure constructor to figure if you want to derive from
77
the default Figure. This simple example creates a figure with a figure title.
88
"""
9-
from matplotlib.pyplot import figure, show
9+
10+
from matplotlib import pyplot as plt
1011
from matplotlib.figure import Figure
1112

1213

@@ -20,8 +21,8 @@ def __init__(self, *args, **kwargs):
2021
self.text(0.5, 0.95, figtitle, ha='center')
2122

2223

23-
fig = figure(FigureClass=MyFigure, figtitle='my title')
24-
ax = fig.add_subplot(111)
24+
fig = plt.figure(FigureClass=MyFigure, figtitle='my title')
25+
ax = fig.subplots()
2526
ax.plot([1, 2, 3])
2627

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

examples/text_labels_and_annotations/mathtext_demo.py

+12-17
Original file line numberDiff line numberDiff line change
@@ -3,29 +3,24 @@
33
Mathtext Demo
44
=============
55
6-
Use matplotlib's internal LaTeX parser and layout engine. For true
7-
latex rendering, see the text.usetex option
6+
Use Matplotlib's internal LaTeX parser and layout engine. For true LaTeX
7+
rendering, see the text.usetex option.
88
"""
9-
import numpy as np
10-
from matplotlib.pyplot import figure, show
119

12-
fig = figure()
13-
fig.subplots_adjust(bottom=0.2)
10+
from matplotlib import pyplot as plt
1411

15-
ax = fig.add_subplot(111)
16-
ax.plot([1, 2, 3], 'r')
17-
x = np.arange(0.0, 3.0, 0.1)
12+
fig, ax = plt.subplots()
13+
14+
ax.plot([1, 2, 3], 'r', label=r'$\sqrt{x^2}$')
15+
ax.legend()
1816

19-
ax.grid(True)
2017
ax.set_xlabel(r'$\Delta_i^j$', fontsize=20)
2118
ax.set_ylabel(r'$\Delta_{i+1}^j$', fontsize=20)
22-
tex = r'$\mathcal{R}\prod_{i=\alpha_{i+1}}^\infty a_i\sin(2 \pi f x_i)$'
23-
24-
ax.text(1, 1.6, tex, fontsize=20, va='bottom')
25-
26-
ax.legend([r"$\sqrt{x^2}$"])
27-
2819
ax.set_title(r'$\Delta_i^j \hspace{0.4} \mathrm{versus} \hspace{0.4} '
2920
r'\Delta_{i+1}^j$', fontsize=20)
3021

31-
show()
22+
tex = r'$\mathcal{R}\prod_{i=\alpha_{i+1}}^\infty a_i\sin(2 \pi f x_i)$'
23+
ax.text(1, 1.6, tex, fontsize=20, va='bottom')
24+
25+
fig.tight_layout()
26+
plt.show()

examples/units/radian_demo.py

+8-9
Original file line numberDiff line numberDiff line change
@@ -13,19 +13,18 @@
1313
1414
This example requires :download:`basic_units.py <basic_units.py>`
1515
"""
16+
17+
from matplotlib import pyplot as plt
1618
import numpy as np
19+
1720
from basic_units import radians, degrees, cos
18-
from matplotlib.pyplot import figure, show
1921

2022
x = [val*radians for val in np.arange(0, 15, 0.01)]
2123

22-
fig = figure()
23-
fig.subplots_adjust(hspace=0.3)
24-
25-
ax = fig.add_subplot(211)
26-
line1, = ax.plot(x, cos(x), xunits=radians)
24+
fig, axs = plt.subplots(2)
2725

28-
ax = fig.add_subplot(212)
29-
line2, = ax.plot(x, cos(x), xunits=degrees)
26+
axs[0].plot(x, cos(x), xunits=radians)
27+
axs[1].plot(x, cos(x), xunits=degrees)
3028

31-
show()
29+
fig.tight_layout()
30+
plt.show()

0 commit comments

Comments
 (0)