Skip to content

Commit e458a46

Browse files
committed
Remove asfileobj=False from a bunch of examples loading sample_data.
Using a file object works just fine. There are some more examples that load bivariate_normal.npy, but they have a bunch of duplicated code that could use some more refactor.
1 parent 0f927c1 commit e458a46

File tree

10 files changed

+40
-49
lines changed

10 files changed

+40
-49
lines changed

examples/frontpage/3D.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
====================
55
66
This example reproduces the frontpage 3D example.
7-
87
"""
98

109
from matplotlib import cbook
@@ -13,8 +12,8 @@
1312
import matplotlib.pyplot as plt
1413
import numpy as np
1514

16-
filename = cbook.get_sample_data('jacksboro_fault_dem.npz', asfileobj=False)
17-
with np.load(filename) as dem:
15+
with cbook.get_sample_data('jacksboro_fault_dem.npz') as file, \
16+
np.load(file) as dem:
1817
z = dem['elevation']
1918
nrows, ncols = z.shape
2019
x = np.linspace(dem['xmin'], dem['xmax'], ncols)

examples/images_contours_and_fields/image_demo.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@
5151

5252
w, h = 512, 512
5353

54-
with cbook.get_sample_data('ct.raw.gz', asfileobj=True) as datafile:
54+
with cbook.get_sample_data('ct.raw.gz') as datafile:
5555
s = datafile.read()
5656
A = np.frombuffer(s, np.uint16).astype(float).reshape((w, h))
5757
A /= A.max()

examples/images_contours_and_fields/shading_example.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,28 @@
11
"""
22
===============
3-
Shading Example
3+
Shading example
44
===============
55
6-
Example showing how to make shaded relief plots
7-
like Mathematica
8-
(http://reference.wolfram.com/mathematica/ref/ReliefPlot.html)
9-
or Generic Mapping Tools
10-
(https://gmt.soest.hawaii.edu/)
6+
Example showing how to make shaded relief plots like Mathematica_ or
7+
`Generic Mapping Tools`_.
8+
9+
.. _Mathematica: http://reference.wolfram.com/mathematica/ref/ReliefPlot.html
10+
.. _Generic Mapping Tools: https://gmt.soest.hawaii.edu/
1111
"""
12+
1213
import numpy as np
14+
from matplotlib import cbook
1315
import matplotlib.pyplot as plt
1416
from matplotlib.colors import LightSource
15-
from matplotlib.cbook import get_sample_data
1617

1718

1819
def main():
1920
# Test data
2021
x, y = np.mgrid[-5:5:0.05, -5:5:0.05]
2122
z = 5 * (np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2))
2223

23-
filename = get_sample_data('jacksboro_fault_dem.npz', asfileobj=False)
24-
with np.load(filename) as dem:
24+
with cbook.get_sample_data('jacksboro_fault_dem.npz') as file, \
25+
np.load(file) as dem:
2526
elev = dem['elevation']
2627

2728
fig = compare(z, plt.cm.copper)

examples/images_contours_and_fields/watermark_image.py

+5-9
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,21 @@
55
66
Using a PNG file as a watermark.
77
"""
8+
89
import numpy as np
910
import matplotlib.cbook as cbook
1011
import matplotlib.image as image
1112
import matplotlib.pyplot as plt
1213

13-
# Fixing random state for reproducibility
14-
np.random.seed(19680801)
15-
1614

17-
datafile = cbook.get_sample_data('logo2.png', asfileobj=False)
18-
print('loading %s' % datafile)
19-
im = image.imread(datafile)
20-
im[:, :, -1] = 0.5 # set the alpha channel
15+
with cbook.get_sample_data('logo2.png') as file:
16+
im = image.imread(file)
2117

2218
fig, ax = plt.subplots()
2319

24-
ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='orange')
20+
ax.plot(np.sin(10 * np.linspace(0, 1)), '-o', ms=20, alpha=0.7, mfc='orange')
2521
ax.grid()
26-
fig.figimage(im, 10, 10, zorder=3)
22+
fig.figimage(im, 10, 10, zorder=3, alpha=.5)
2723

2824
plt.show()
2925

examples/misc/load_converter.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,10 @@
1313
import numpy as np
1414

1515

16-
datafile = cbook.get_sample_data('msft.csv', asfileobj=False)
17-
print('loading', datafile)
18-
19-
data = np.genfromtxt(
20-
datafile, delimiter=',', names=True,
21-
dtype=None, converters={0: dateutil.parser.parse})
16+
with cbook.get_sample_data('msft.csv') as file:
17+
data = np.genfromtxt(
18+
file, delimiter=',', names=True,
19+
dtype=None, converters={0: dateutil.parser.parse})
2220

2321
fig, ax = plt.subplots()
2422
ax.plot(data['Date'], data['High'], '-')

examples/mplot3d/custom_shaded_3d_surface.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
import numpy as np
1414

1515
# Load and format data
16-
filename = cbook.get_sample_data('jacksboro_fault_dem.npz', asfileobj=False)
17-
with np.load(filename) as dem:
16+
with cbook.get_sample_data('jacksboro_fault_dem.npz') as file, \
17+
np.load(file) as dem:
1818
z = dem['elevation']
1919
nrows, ncols = z.shape
2020
x = np.linspace(dem['xmin'], dem['xmax'], ncols)

examples/showcase/bachelors_degrees_by_gender.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,8 @@
1515
from matplotlib.cbook import get_sample_data
1616

1717

18-
fname = get_sample_data('percent_bachelors_degrees_women_usa.csv',
19-
asfileobj=False)
20-
gender_degree_data = np.genfromtxt(fname, delimiter=',', names=True)
18+
with get_sample_data('percent_bachelors_degrees_women_usa.csv') as file:
19+
gender_degree_data = np.genfromtxt(file, delimiter=',', names=True)
2120

2221
# You typically want your plot to be ~1.33x wider than tall. This plot
2322
# is a rare exception because of the number of lines being plotted on it.

examples/text_labels_and_annotations/demo_annotation_box.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,8 @@
7777
ax.add_artist(ab)
7878

7979
# Annotate the 2nd position with another image (a Grace Hopper portrait)
80-
fn = get_sample_data("grace_hopper.png", asfileobj=False)
81-
arr_img = plt.imread(fn, format='png')
80+
with get_sample_data("grace_hopper.png") as file:
81+
arr_img = plt.imread(file, format='png')
8282

8383
imagebox = OffsetImage(arr_img, zoom=0.2)
8484
imagebox.image.axes = ax

examples/ticks_and_spines/date_index_formatter2.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,10 @@
1818
import numpy as np
1919

2020

21-
datafile = cbook.get_sample_data('msft.csv', asfileobj=False)
22-
print('loading %s' % datafile)
23-
msft_data = np.genfromtxt(
24-
datafile, delimiter=',', names=True,
25-
converters={0: lambda s: dates.date2num(dateutil.parser.parse(s))})
21+
with cbook.get_sample_data('msft.csv') as file:
22+
msft_data = np.genfromtxt(
23+
file, delimiter=',', names=True,
24+
converters={0: lambda s: dates.date2num(dateutil.parser.parse(s))})
2625

2726

2827
class MyFormatter(Formatter):

lib/matplotlib/tests/test_colors.py

+8-9
Original file line numberDiff line numberDiff line change
@@ -391,15 +391,14 @@ def test_colors_no_float():
391391
extensions=['png'])
392392
def test_light_source_topo_surface():
393393
"""Shades a DEM using different v.e.'s and blend modes."""
394-
fname = cbook.get_sample_data('jacksboro_fault_dem.npz', asfileobj=False)
395-
dem = np.load(fname)
396-
elev = dem['elevation']
397-
# Get the true cellsize in meters for accurate vertical exaggeration
398-
# Convert from decimal degrees to meters
399-
dx, dy = dem['dx'], dem['dy']
400-
dx = 111320.0 * dx * np.cos(dem['ymin'])
401-
dy = 111320.0 * dy
402-
dem.close()
394+
with cbook.get_sample_data('jacksboro_fault_dem.npz') as file, \
395+
np.load(file) as dem:
396+
elev = dem['elevation']
397+
dx, dy = dem['dx'], dem['dy']
398+
# Get the true cellsize in meters for accurate vertical exaggeration
399+
# Convert from decimal degrees to meters
400+
dx = 111320.0 * dx * np.cos(dem['ymin'])
401+
dy = 111320.0 * dy
403402

404403
ls = mcolors.LightSource(315, 45)
405404
cmap = cm.gist_earth

0 commit comments

Comments
 (0)