Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a1c51a0

Browse files
authored
Merge pull request #15641 from anntzer/get_sample_data-npy
API: Make get_sample_data autoload npy/npz files.
2 parents 56d509f + d7d11a7 commit a1c51a0

File tree

24 files changed

+102
-130
lines changed

24 files changed

+102
-130
lines changed

doc/api/api_changes_3.3/behaviour.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,3 +294,10 @@ FT_LOAD_DEFAULT, etc. The old synonyms (respectively "either", "native",
294294
"auto", and "none") are still supported, but their use is discouraged. To get
295295
normalized values, use `.backend_agg.get_hinting_flag`, which returns integer
296296
flag values.
297+
298+
`.cbook.get_sample_data` auto-loads numpy arrays
299+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
300+
When `.cbook.get_sample_data` is used to load a npy or npz file and the
301+
keyword-only parameter ``np_load`` is True, the file is automatically loaded
302+
using `numpy.load`. ``np_load`` defaults to False for backwards compatibility,
303+
but will become True in a later release.

examples/axes_grid1/demo_axes_divider.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,13 @@
66
Axes divider to calculate location of axes and
77
create a divider for them using existing axes instances.
88
"""
9+
10+
from matplotlib import cbook
911
import matplotlib.pyplot as plt
1012

1113

1214
def get_demo_image():
13-
import numpy as np
14-
from matplotlib.cbook import get_sample_data
15-
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
16-
z = np.load(f)
15+
z = cbook.get_sample_data("axes_grid/bivariate_normal.npy", np_load=True)
1716
# z is a numpy array of 15x15
1817
return z, (-3, 4, -4, 3)
1918

examples/axes_grid1/demo_axes_grid.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
Grid of 2x2 images with single or own colorbar.
77
"""
88

9+
from matplotlib import cbook
910
import matplotlib.pyplot as plt
1011
from mpl_toolkits.axes_grid1 import ImageGrid
1112

@@ -14,10 +15,7 @@
1415

1516

1617
def get_demo_image():
17-
import numpy as np
18-
from matplotlib.cbook import get_sample_data
19-
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
20-
z = np.load(f)
18+
z = cbook.get_sample_data("axes_grid/bivariate_normal.npy", np_load=True)
2119
# z is a numpy array of 15x15
2220
return z, (-3, 4, -4, 3)
2321

examples/axes_grid1/demo_axes_grid2.py

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,15 @@
77
"""
88

99
import numpy as np
10-
10+
from matplotlib import cbook
11+
import matplotlib.colors
1112
import matplotlib.pyplot as plt
1213
from mpl_toolkits.axes_grid1 import ImageGrid
13-
import matplotlib.colors
1414

1515

1616
plt.rcParams["mpl_toolkits.legacy_colorbar"] = False
1717

1818

19-
def get_demo_image():
20-
from matplotlib.cbook import get_sample_data
21-
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
22-
z = np.load(f)
23-
# z is a numpy array of 15x15
24-
return z, (-3, 4, -4, 3)
25-
26-
2719
def add_inner_title(ax, title, loc, **kwargs):
2820
from matplotlib.offsetbox import AnchoredText
2921
from matplotlib.patheffects import withStroke
@@ -39,7 +31,8 @@ def add_inner_title(ax, title, loc, **kwargs):
3931
fig = plt.figure(figsize=(6, 6))
4032

4133
# Prepare images
42-
Z, extent = get_demo_image()
34+
Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy", np_load=True)
35+
extent = (-3, 4, -4, 3)
4336
ZS = [Z[i::3, :] for i in range(3)]
4437
extent = extent[0], extent[1]/3., extent[2], extent[3]
4538

examples/axes_grid1/demo_axes_rgb.py

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

1414

1515
def get_rgb():
16-
f = cbook.get_sample_data("axes_grid/bivariate_normal.npy")
17-
Z = np.load(f) # 15x15 numpy array.
18-
16+
Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy", np_load=True)
1917
Z[Z < 0] = 0.
2018
Z = Z / Z.max()
2119

examples/axes_grid1/demo_colorbar_of_inset_axes.py

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,36 +4,25 @@
44
===========================
55
66
"""
7-
import matplotlib.pyplot as plt
87

8+
from matplotlib import cbook
9+
import matplotlib.pyplot as plt
910
from mpl_toolkits.axes_grid1.inset_locator import inset_axes, zoomed_inset_axes
1011

1112

12-
def get_demo_image():
13-
from matplotlib.cbook import get_sample_data
14-
import numpy as np
15-
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
16-
z = np.load(f)
17-
# z is a numpy array of 15x15
18-
return z, (-3, 4, -4, 3)
19-
20-
2113
fig, ax = plt.subplots(figsize=[5, 4])
2214

23-
Z, extent = get_demo_image()
24-
25-
ax.set(aspect=1,
26-
xlim=(-15, 15),
27-
ylim=(-20, 5))
15+
Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy", np_load=True)
16+
extent = (-3, 4, -4, 3)
2817

18+
ax.set(aspect=1, xlim=(-15, 15), ylim=(-20, 5))
2919

3020
axins = zoomed_inset_axes(ax, zoom=2, loc='upper left')
3121
im = axins.imshow(Z, extent=extent, origin="lower")
3222

3323
plt.xticks(visible=False)
3424
plt.yticks(visible=False)
3525

36-
3726
# colorbar
3827
cax = inset_axes(axins,
3928
width="5%", # width = 10% of parent_bbox width
@@ -43,7 +32,6 @@ def get_demo_image():
4332
bbox_transform=axins.transAxes,
4433
borderpad=0,
4534
)
46-
4735
fig.colorbar(im, cax=cax)
4836

4937
plt.show()

examples/axes_grid1/demo_edge_colorbar.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
of an image grid.
88
"""
99

10+
from matplotlib import cbook
1011
import matplotlib.pyplot as plt
1112
from mpl_toolkits.axes_grid1 import AxesGrid
1213

@@ -15,10 +16,7 @@
1516

1617

1718
def get_demo_image():
18-
import numpy as np
19-
from matplotlib.cbook import get_sample_data
20-
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
21-
z = np.load(f)
19+
z = cbook.get_sample_data("axes_grid/bivariate_normal.npy", np_load=True)
2220
# z is a numpy array of 15x15
2321
return z, (-3, 4, -4, 3)
2422

examples/axes_grid1/inset_locator_demo2.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,16 @@
99
created via `~.mark_inset`.
1010
"""
1111

12+
from matplotlib import cbook
1213
import matplotlib.pyplot as plt
13-
1414
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset
1515
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
1616

1717
import numpy as np
1818

1919

2020
def get_demo_image():
21-
from matplotlib.cbook import get_sample_data
22-
import numpy as np
23-
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
24-
z = np.load(f)
21+
z = cbook.get_sample_data("axes_grid/bivariate_normal.npy", np_load=True)
2522
# z is a numpy array of 15x15
2623
return z, (-3, 4, -4, 3)
2724

@@ -60,11 +57,9 @@ def add_sizebar(ax, size):
6057
ny, nx = Z.shape
6158
Z2[30:30+ny, 30:30+nx] = Z
6259

63-
# extent = [-3, 4, -4, 3]
6460
ax2.imshow(Z2, extent=extent, origin="lower")
6561

66-
67-
axins2 = zoomed_inset_axes(ax2, 6, loc=1) # zoom = 6
62+
axins2 = zoomed_inset_axes(ax2, zoom=6, loc=1)
6863
axins2.imshow(Z2, extent=extent, origin="lower")
6964

7065
# sub region of the original image

examples/axes_grid1/simple_axesgrid2.py

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,28 +6,21 @@
66
Align multiple images of different sizes using
77
`~mpl_toolkits.axes_grid1.axes_grid.ImageGrid`.
88
"""
9+
10+
from matplotlib import cbook
911
import matplotlib.pyplot as plt
1012
from mpl_toolkits.axes_grid1 import ImageGrid
1113

1214

13-
def get_demo_image():
14-
import numpy as np
15-
from matplotlib.cbook import get_sample_data
16-
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
17-
z = np.load(f)
18-
# z is a numpy array of 15x15
19-
return z, (-3, 4, -4, 3)
20-
21-
2215
fig = plt.figure(figsize=(5.5, 3.5))
2316
grid = ImageGrid(fig, 111, # similar to subplot(111)
2417
nrows_ncols=(1, 3),
2518
axes_pad=0.1,
2619
label_mode="L",
2720
)
2821

29-
Z, extent = get_demo_image() # demo image
30-
22+
# demo image
23+
Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy", np_load=True)
3124
im1 = Z
3225
im2 = Z[:, :10]
3326
im3 = Z[:, 10:]

examples/frontpage/3D.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,12 @@
1212
import matplotlib.pyplot as plt
1313
import numpy as np
1414

15-
with cbook.get_sample_data('jacksboro_fault_dem.npz') as file, \
16-
np.load(file) as dem:
17-
z = dem['elevation']
18-
nrows, ncols = z.shape
19-
x = np.linspace(dem['xmin'], dem['xmax'], ncols)
20-
y = np.linspace(dem['ymin'], dem['ymax'], nrows)
21-
x, y = np.meshgrid(x, y)
15+
dem = cbook.get_sample_data('jacksboro_fault_dem.npz', np_load=True)
16+
z = dem['elevation']
17+
nrows, ncols = z.shape
18+
x = np.linspace(dem['xmin'], dem['xmax'], ncols)
19+
y = np.linspace(dem['ymin'], dem['ymax'], nrows)
20+
x, y = np.meshgrid(x, y)
2221

2322
region = np.s_[5:50, 5:50]
2423
x, y, z = x[region], y[region], z[region]

examples/images_contours_and_fields/shading_example.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,8 @@ def main():
2121
x, y = np.mgrid[-5:5:0.05, -5:5:0.05]
2222
z = 5 * (np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2))
2323

24-
with cbook.get_sample_data('jacksboro_fault_dem.npz') as file, \
25-
np.load(file) as dem:
26-
elev = dem['elevation']
24+
dem = cbook.get_sample_data('jacksboro_fault_dem.npz', np_load=True)
25+
elev = dem['elevation']
2726

2827
fig = compare(z, plt.cm.copper)
2928
fig.suptitle('HSV Blending Looks Best with Smooth Surfaces', y=0.95)

examples/lines_bars_and_markers/scatter_demo2.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212
# Load a numpy record array from yahoo csv data with fields date, open, close,
1313
# volume, adj_close from the mpl-data/example directory. The record array
1414
# stores the date as an np.datetime64 with a day unit ('D') in the date column.
15-
with cbook.get_sample_data('goog.npz') as datafile:
16-
price_data = np.load(datafile)['price_data'].view(np.recarray)
15+
price_data = (cbook.get_sample_data('goog.npz', np_load=True)['price_data']
16+
.view(np.recarray))
1717
price_data = price_data[-250:] # get the most recent 250 trading days
1818

1919
delta1 = np.diff(price_data.adj_close) / price_data.adj_close[:-1]

examples/mplot3d/custom_shaded_3d_surface.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,12 @@
1313
import numpy as np
1414

1515
# Load and format data
16-
with cbook.get_sample_data('jacksboro_fault_dem.npz') as file, \
17-
np.load(file) as dem:
18-
z = dem['elevation']
19-
nrows, ncols = z.shape
20-
x = np.linspace(dem['xmin'], dem['xmax'], ncols)
21-
y = np.linspace(dem['ymin'], dem['ymax'], nrows)
22-
x, y = np.meshgrid(x, y)
16+
dem = cbook.get_sample_data('jacksboro_fault_dem.npz', np_load=True)
17+
z = dem['elevation']
18+
nrows, ncols = z.shape
19+
x = np.linspace(dem['xmin'], dem['xmax'], ncols)
20+
y = np.linspace(dem['ymin'], dem['ymax'], nrows)
21+
x, y = np.meshgrid(x, y)
2322

2423
region = np.s_[5:50, 5:50]
2524
x, y, z = x[region], y[region], z[region]

examples/recipes/common_date_problems.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,8 @@
3838
import numpy as np
3939
import matplotlib.pyplot as plt
4040

41-
with cbook.get_sample_data('goog.npz') as datafile:
42-
r = np.load(datafile)['price_data'].view(np.recarray)
41+
r = (cbook.get_sample_data('goog.npz', np_load=True)['price_data']
42+
.view(np.recarray))
4343

4444
fig, ax = plt.subplots()
4545
ax.plot(r.date, r.close)

examples/recipes/fill_between_alpha.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@
2121
np.random.seed(19680801)
2222

2323
# load up some sample financial data
24-
with cbook.get_sample_data('goog.npz') as datafile:
25-
r = np.load(datafile)['price_data'].view(np.recarray)
24+
r = (cbook.get_sample_data('goog.npz', np_load=True)['price_data']
25+
.view(np.recarray))
2626
# create two subplots with the shared x and y axes
2727
fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)
2828

examples/specialty_plots/topographic_hillshading.py

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -22,23 +22,21 @@
2222
from matplotlib.colors import LightSource
2323

2424

25-
with np.load(get_sample_data('jacksboro_fault_dem.npz')) as dem:
26-
z = dem['elevation']
27-
28-
#-- Optional dx and dy for accurate vertical exaggeration ----------------
29-
# If you need topographically accurate vertical exaggeration, or you don't
30-
# want to guess at what *vert_exag* should be, you'll need to specify the
31-
# cellsize of the grid (i.e. the *dx* and *dy* parameters). Otherwise, any
32-
# *vert_exag* value you specify will be relative to the grid spacing of
33-
# your input data (in other words, *dx* and *dy* default to 1.0, and
34-
# *vert_exag* is calculated relative to those parameters). Similarly, *dx*
35-
# and *dy* are assumed to be in the same units as your input z-values.
36-
# Therefore, we'll need to convert the given dx and dy from decimal degrees
37-
# to meters.
38-
dx, dy = dem['dx'], dem['dy']
39-
dy = 111200 * dy
40-
dx = 111200 * dx * np.cos(np.radians(dem['ymin']))
41-
#-------------------------------------------------------------------------
25+
dem = get_sample_data('jacksboro_fault_dem.npz', np_load=True)
26+
z = dem['elevation']
27+
#-- Optional dx and dy for accurate vertical exaggeration ---------------------
28+
# If you need topographically accurate vertical exaggeration, or you don't want
29+
# to guess at what *vert_exag* should be, you'll need to specify the cellsize
30+
# of the grid (i.e. the *dx* and *dy* parameters). Otherwise, any *vert_exag*
31+
# value you specify will be relative to the grid spacing of your input data
32+
# (in other words, *dx* and *dy* default to 1.0, and *vert_exag* is calculated
33+
# relative to those parameters). Similarly, *dx* and *dy* are assumed to be in
34+
# the same units as your input z-values. Therefore, we'll need to convert the
35+
# given dx and dy from decimal degrees to meters.
36+
dx, dy = dem['dx'], dem['dy']
37+
dy = 111200 * dy
38+
dx = 111200 * dx * np.cos(np.radians(dem['ymin']))
39+
#------------------------------------------------------------------------------
4240

4341
# Shade from the northwest, with the sun 45 degrees from horizontal
4442
ls = LightSource(azdeg=315, altdeg=45)

examples/subplots_axes_and_figures/zoom_inset_axes.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,15 @@
44
======================
55
66
Example of an inset axes and a rectangle showing where the zoom is located.
7-
87
"""
98

9+
from matplotlib import cbook
1010
import matplotlib.pyplot as plt
1111
import numpy as np
1212

1313

1414
def get_demo_image():
15-
from matplotlib.cbook import get_sample_data
16-
import numpy as np
17-
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
18-
z = np.load(f)
15+
z = cbook.get_sample_data("axes_grid/bivariate_normal.npy", np_load=True)
1916
# z is a numpy array of 15x15
2017
return z, (-3, 4, -4, 3)
2118

examples/text_labels_and_annotations/date.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,7 @@
2929
# close, volume, adj_close from the mpl-data/example directory. This array
3030
# stores the date as an np.datetime64 with a day unit ('D') in the 'date'
3131
# column.
32-
with cbook.get_sample_data('goog.npz') as datafile:
33-
data = np.load(datafile)['price_data']
32+
data = cbook.get_sample_data('goog.npz', np_load=True)['price_data']
3433

3534
fig, ax = plt.subplots()
3635
ax.plot('date', 'adj_close', data=data)

examples/text_labels_and_annotations/date_index_formatter.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@
1414
# Load a numpy record array from yahoo csv data with fields date, open, close,
1515
# volume, adj_close from the mpl-data/example directory. The record array
1616
# stores the date as an np.datetime64 with a day unit ('D') in the date column.
17-
with cbook.get_sample_data('goog.npz') as datafile:
18-
r = np.load(datafile)['price_data'].view(np.recarray)
17+
r = (cbook.get_sample_data('goog.npz', np_load=True)['price_data']
18+
.view(np.recarray))
1919
r = r[-30:] # get the last 30 days
2020

2121
# first we'll do it the default way, with gaps on weekends

0 commit comments

Comments
 (0)