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

Skip to content

Commit c1781ec

Browse files
authored
Merge pull request #10603 from anntzer/np110
Remove workarounds for numpy<1.10.
2 parents bad022e + 6385ccf commit c1781ec

28 files changed

+131
-318
lines changed

examples/api/custom_projection_example.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -395,18 +395,17 @@ def __init__(self, resolution):
395395
self._resolution = resolution
396396

397397
def transform_non_affine(self, ll):
398-
longitude = ll[:, 0:1]
399-
latitude = ll[:, 1:2]
398+
longitude, latitude = ll.T
400399

401400
# Pre-compute some values
402-
half_long = longitude / 2.0
401+
half_long = longitude / 2
403402
cos_latitude = np.cos(latitude)
404-
sqrt2 = np.sqrt(2.0)
403+
sqrt2 = np.sqrt(2)
405404

406-
alpha = np.sqrt(1.0 + cos_latitude * np.cos(half_long))
407-
x = (2.0 * sqrt2) * (cos_latitude * np.sin(half_long)) / alpha
405+
alpha = np.sqrt(1 + cos_latitude * np.cos(half_long))
406+
x = (2 * sqrt2) * (cos_latitude * np.sin(half_long)) / alpha
408407
y = (sqrt2 * np.sin(latitude)) / alpha
409-
return np.concatenate((x, y), 1)
408+
return np.column_stack([x, y])
410409
transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__
411410

412411
def transform_path_non_affine(self, path):

examples/misc/demo_ribbon_box.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def __init__(self, color):
3030
self.original_image.dtype)
3131

3232
im[:, :, :3] = self.b_and_h[:, :, np.newaxis]
33-
im[:, :, :3] -= self.color[:, :, np.newaxis]*(1. - np.array(rgb))
33+
im[:, :, :3] -= self.color[:, :, np.newaxis] * (1 - np.array(rgb))
3434
im[:, :, 3] = self.alpha
3535

3636
self.im = im

examples/mplot3d/hist3d.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,14 @@
2020
hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]])
2121

2222
# Construct arrays for the anchor positions of the 16 bars.
23-
# Note: np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos,
24-
# ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid
25-
# with indexing='ij'.
26-
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25)
27-
xpos = xpos.flatten('F')
28-
ypos = ypos.flatten('F')
29-
zpos = np.zeros_like(xpos)
23+
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25, indexing="ij")
24+
xpos = xpos.ravel()
25+
ypos = ypos.ravel()
26+
zpos = 0
3027

3128
# Construct arrays with the dimensions for the 16 bars.
32-
dx = 0.5 * np.ones_like(zpos)
33-
dy = dx.copy()
34-
dz = hist.flatten()
29+
dx = dy = 0.5 * np.ones_like(zpos)
30+
dz = hist.ravel()
3531

3632
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')
3733

examples/mplot3d/trisurf3d.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,7 @@
1616

1717
# Make radii and angles spaces (radius r=0 omitted to eliminate duplication).
1818
radii = np.linspace(0.125, 1.0, n_radii)
19-
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
20-
21-
# Repeat all angles for each radius.
22-
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
19+
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)[..., np.newaxis]
2320

2421
# Convert polar (radii, angles) coords to cartesian (x, y) coords.
2522
# (0, 0) is manually added at this stage, so there will be no duplicate

examples/pyplots/boxplot_demo_pyplot.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
center = np.ones(25) * 50
1818
flier_high = np.random.rand(10) * 100 + 100
1919
flier_low = np.random.rand(10) * -100
20-
data = np.concatenate((spread, center, flier_high, flier_low), 0)
20+
data = np.concatenate((spread, center, flier_high, flier_low))
2121

2222
###############################################################################
2323

@@ -64,7 +64,7 @@
6464
center = np.ones(25) * 40
6565
flier_high = np.random.rand(10) * 100 + 100
6666
flier_low = np.random.rand(10) * -100
67-
d2 = np.concatenate((spread, center, flier_high, flier_low), 0)
67+
d2 = np.concatenate((spread, center, flier_high, flier_low))
6868
data.shape = (-1, 1)
6969
d2.shape = (-1, 1)
7070

examples/shapes_and_collections/ellipse_collection.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
y = np.arange(15)
1313
X, Y = np.meshgrid(x, y)
1414

15-
XY = np.hstack((X.ravel()[:, np.newaxis], Y.ravel()[:, np.newaxis]))
15+
XY = np.column_stack((X.ravel(), Y.ravel()))
1616

1717
ww = X / 10.0
1818
hh = Y / 15.0

examples/shapes_and_collections/line_collection.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
# Here are many sets of y to plot vs x
2323
ys = x[:50, np.newaxis] + x[np.newaxis, :]
2424

25-
segs = np.zeros((50, 100, 2), float)
25+
segs = np.zeros((50, 100, 2))
2626
segs[:, :, 1] = ys
2727
segs[:, :, 0] = x
2828

examples/specialty_plots/mri_with_eeg.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,10 @@
4040
ax1.set_ylabel('MRI density')
4141

4242
# Load the EEG data
43-
numSamples, numRows = 800, 4
43+
n_samples, n_rows = 800, 4
4444
with cbook.get_sample_data('eeg.dat') as eegfile:
45-
data = np.fromfile(eegfile, dtype=float)
46-
data.shape = (numSamples, numRows)
47-
t = 10.0 * np.arange(numSamples) / numSamples
45+
data = np.fromfile(eegfile, dtype=float).reshape((n_samples, n_rows))
46+
t = 10 * np.arange(n_samples) / n_samples
4847

4948
# Plot the EEG
5049
ticklocs = []
@@ -55,15 +54,15 @@
5554
dmax = data.max()
5655
dr = (dmax - dmin) * 0.7 # Crowd them a bit.
5756
y0 = dmin
58-
y1 = (numRows - 1) * dr + dmax
57+
y1 = (n_rows - 1) * dr + dmax
5958
ax2.set_ylim(y0, y1)
6059

6160
segs = []
62-
for i in range(numRows):
63-
segs.append(np.hstack((t[:, np.newaxis], data[:, i, np.newaxis])))
61+
for i in range(n_rows):
62+
segs.append(np.column_stack((t, data[:, i])))
6463
ticklocs.append(i * dr)
6564

66-
offsets = np.zeros((numRows, 2), dtype=float)
65+
offsets = np.zeros((n_rows, 2), dtype=float)
6766
offsets[:, 1] = ticklocs
6867

6968
lines = LineCollection(segs, offsets=offsets, transOffset=None)

examples/statistics/boxplot_demo.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
center = np.ones(25) * 50
2424
flier_high = np.random.rand(10) * 100 + 100
2525
flier_low = np.random.rand(10) * -100
26-
data = np.concatenate((spread, center, flier_high, flier_low), 0)
26+
data = np.concatenate((spread, center, flier_high, flier_low))
2727

2828
fig, axs = plt.subplots(2, 3)
2929

@@ -59,7 +59,7 @@
5959
center = np.ones(25) * 40
6060
flier_high = np.random.rand(10) * 100 + 100
6161
flier_low = np.random.rand(10) * -100
62-
d2 = np.concatenate((spread, center, flier_high, flier_low), 0)
62+
d2 = np.concatenate((spread, center, flier_high, flier_low))
6363
data.shape = (-1, 1)
6464
d2.shape = (-1, 1)
6565
# Making a 2-D array only works if all the columns are the

lib/matplotlib/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,8 @@
141141
# definitions, so it is safe to import from it here.
142142
from . import cbook
143143
from matplotlib.cbook import (
144-
_backports, mplDeprecation, dedent, get_label, sanitize_sequence)
144+
mplDeprecation, dedent, get_label, sanitize_sequence)
145+
from matplotlib.compat import subprocess
145146
from matplotlib.rcsetup import defaultParams, validate_backend, cycler
146147

147148
import numpy
@@ -156,7 +157,7 @@
156157

157158
_log = logging.getLogger(__name__)
158159

159-
__version__numpy__ = str('1.10.0') # minimum required numpy version
160+
__version__numpy__ = '1.10.0' # minimum required numpy version
160161

161162
__bibtex__ = r"""@Article{Hunter:2007,
162163
Author = {Hunter, J. D.},

lib/matplotlib/axes/_axes.py

Lines changed: 19 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,8 @@
4040
import matplotlib.transforms as mtransforms
4141
import matplotlib.tri as mtri
4242
from matplotlib.cbook import (
43-
_backports, mplDeprecation, warn_deprecated,
44-
STEP_LOOKUP_MAP, iterable, safe_first_element)
43+
mplDeprecation, warn_deprecated, STEP_LOOKUP_MAP, iterable,
44+
safe_first_element)
4545
from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer
4646
from matplotlib.axes._base import _AxesBase, _process_plot_format
4747

@@ -2318,7 +2318,7 @@ def bar(self, *args, **kwargs):
23182318
self.add_container(bar_container)
23192319

23202320
if tick_labels is not None:
2321-
tick_labels = _backports.broadcast_to(tick_labels, len(patches))
2321+
tick_labels = np.broadcast_to(tick_labels, len(patches))
23222322
tick_label_axis.set_ticks(tick_label_position)
23232323
tick_label_axis.set_ticklabels(tick_labels)
23242324

@@ -3177,16 +3177,10 @@ def errorbar(self, x, y, yerr=None, xerr=None,
31773177
caplines = []
31783178

31793179
# arrays fine here, they are booleans and hence not units
3180-
def _bool_asarray_helper(d, expected):
3181-
if not iterable(d):
3182-
return np.asarray([d] * expected, bool)
3183-
else:
3184-
return np.asarray(d, bool)
3185-
3186-
lolims = _bool_asarray_helper(lolims, len(x))
3187-
uplims = _bool_asarray_helper(uplims, len(x))
3188-
xlolims = _bool_asarray_helper(xlolims, len(x))
3189-
xuplims = _bool_asarray_helper(xuplims, len(x))
3180+
lolims = np.broadcast_to(lolims, len(x)).astype(bool)
3181+
uplims = np.broadcast_to(uplims, len(x)).astype(bool)
3182+
xlolims = np.broadcast_to(xlolims, len(x)).astype(bool)
3183+
xuplims = np.broadcast_to(xuplims, len(x)).astype(bool)
31903184

31913185
everymask = np.arange(len(x)) % errorevery == 0
31923186

@@ -3218,9 +3212,9 @@ def extract_err(err, data):
32183212
else:
32193213
if iterable(a) and iterable(b):
32203214
# using list comps rather than arrays to preserve units
3221-
low = [thisx - thiserr for (thisx, thiserr)
3215+
low = [thisx - thiserr for thisx, thiserr
32223216
in cbook.safezip(data, a)]
3223-
high = [thisx + thiserr for (thisx, thiserr)
3217+
high = [thisx + thiserr for thisx, thiserr
32243218
in cbook.safezip(data, b)]
32253219
return low, high
32263220
# Check if xerr is scalar or symmetric. Asymmetric is handled
@@ -3229,13 +3223,13 @@ def extract_err(err, data):
32293223
# special case for empty lists
32303224
if len(err) > 1:
32313225
fe = safe_first_element(err)
3232-
if (len(err) != len(data) or np.size(fe) > 1):
3226+
if len(err) != len(data) or np.size(fe) > 1:
32333227
raise ValueError("err must be [ scalar | N, Nx1 "
32343228
"or 2xN array-like ]")
32353229
# using list comps rather than arrays to preserve units
3236-
low = [thisx - thiserr for (thisx, thiserr)
3230+
low = [thisx - thiserr for thisx, thiserr
32373231
in cbook.safezip(data, err)]
3238-
high = [thisx + thiserr for (thisx, thiserr)
3232+
high = [thisx + thiserr for thisx, thiserr
32393233
in cbook.safezip(data, err)]
32403234
return low, high
32413235

@@ -5734,26 +5728,20 @@ def pcolor(self, *args, **kwargs):
57345728
# don't plot if C or any of the surrounding vertices are masked.
57355729
mask = ma.getmaskarray(C) + xymask
57365730

5737-
newaxis = np.newaxis
57385731
compress = np.compress
57395732

57405733
ravelmask = (mask == 0).ravel()
5741-
X1 = compress(ravelmask, ma.filled(X[0:-1, 0:-1]).ravel())
5742-
Y1 = compress(ravelmask, ma.filled(Y[0:-1, 0:-1]).ravel())
5743-
X2 = compress(ravelmask, ma.filled(X[1:, 0:-1]).ravel())
5744-
Y2 = compress(ravelmask, ma.filled(Y[1:, 0:-1]).ravel())
5734+
X1 = compress(ravelmask, ma.filled(X[:-1, :-1]).ravel())
5735+
Y1 = compress(ravelmask, ma.filled(Y[:-1, :-1]).ravel())
5736+
X2 = compress(ravelmask, ma.filled(X[1:, :-1]).ravel())
5737+
Y2 = compress(ravelmask, ma.filled(Y[1:, :-1]).ravel())
57455738
X3 = compress(ravelmask, ma.filled(X[1:, 1:]).ravel())
57465739
Y3 = compress(ravelmask, ma.filled(Y[1:, 1:]).ravel())
5747-
X4 = compress(ravelmask, ma.filled(X[0:-1, 1:]).ravel())
5748-
Y4 = compress(ravelmask, ma.filled(Y[0:-1, 1:]).ravel())
5740+
X4 = compress(ravelmask, ma.filled(X[:-1, 1:]).ravel())
5741+
Y4 = compress(ravelmask, ma.filled(Y[:-1, 1:]).ravel())
57495742
npoly = len(X1)
57505743

5751-
xy = np.concatenate((X1[:, newaxis], Y1[:, newaxis],
5752-
X2[:, newaxis], Y2[:, newaxis],
5753-
X3[:, newaxis], Y3[:, newaxis],
5754-
X4[:, newaxis], Y4[:, newaxis],
5755-
X1[:, newaxis], Y1[:, newaxis]),
5756-
axis=1)
5744+
xy = np.stack([X1, Y1, X2, Y2, X3, Y3, X4, Y4, X1, Y1], axis=-1)
57575745
verts = xy.reshape((npoly, 5, 2))
57585746

57595747
C = compress(ravelmask, ma.filled(C[0:Ny - 1, 0:Nx - 1]).ravel())

lib/matplotlib/axes/_base.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -341,8 +341,7 @@ def _makefill(self, x, y, kw, kwargs):
341341
# modify the kwargs dictionary.
342342
self._setdefaults(default_dict, kwargs)
343343

344-
seg = mpatches.Polygon(np.hstack((x[:, np.newaxis],
345-
y[:, np.newaxis])),
344+
seg = mpatches.Polygon(np.column_stack((x, y)),
346345
facecolor=facecolor,
347346
fill=kwargs.get('fill', True),
348347
closed=kw['closed'])

lib/matplotlib/category.py

Lines changed: 11 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
Module that allows plotting of string "category" data. i.e.
43
``plot(['d', 'f', 'a'],[1, 2, 3])`` will plot three points with x-axis
@@ -11,26 +10,15 @@
1110
strings to integers, provides a tick locator and formatter, and the
1211
class:`.UnitData` that creates and stores the string-to-integer mapping.
1312
"""
14-
from __future__ import (absolute_import, division, print_function,
15-
unicode_literals)
1613

1714
from collections import OrderedDict
1815
import itertools
1916

20-
import six
21-
22-
2317
import numpy as np
2418

2519
import matplotlib.units as units
2620
import matplotlib.ticker as ticker
2721

28-
# np 1.6/1.7 support
29-
from distutils.version import LooseVersion
30-
31-
VALID_TYPES = tuple(set(six.string_types +
32-
(bytes, six.text_type, np.str_, np.bytes_)))
33-
3422

3523
class StrCategoryConverter(units.ConversionInterface):
3624
@staticmethod
@@ -58,7 +46,7 @@ def convert(value, unit, axis):
5846

5947
# pass through sequence of non binary numbers
6048
if all((units.ConversionInterface.is_numlike(v) and
61-
not isinstance(v, VALID_TYPES)) for v in values):
49+
not isinstance(v, (str, bytes))) for v in values):
6250
return np.asarray(values, dtype=float)
6351

6452
# force an update so it also does type checking
@@ -96,7 +84,7 @@ def axisinfo(unit, axis):
9684

9785
@staticmethod
9886
def default_units(data, axis):
99-
""" Sets and updates the :class:`~matplotlib.Axis.axis~ units
87+
"""Sets and updates the :class:`~matplotlib.Axis.axis` units.
10088
10189
Parameters
10290
----------
@@ -156,28 +144,27 @@ def __call__(self, x, pos=None):
156144

157145
@staticmethod
158146
def _text(value):
159-
"""Converts text values into `utf-8` or `ascii` strings
147+
"""Converts text values into utf-8 or ascii strings.
160148
"""
161-
if LooseVersion(np.__version__) < LooseVersion('1.7.0'):
162-
if (isinstance(value, (six.text_type, np.unicode))):
163-
value = value.encode('utf-8', 'ignore').decode('utf-8')
164-
if isinstance(value, (np.bytes_, six.binary_type)):
149+
if isinstance(value, bytes):
165150
value = value.decode(encoding='utf-8')
166-
elif not isinstance(value, (np.str_, six.string_types)):
151+
elif not isinstance(value, str):
167152
value = str(value)
168153
return value
169154

170155

171156
class UnitData(object):
172157
def __init__(self, data=None):
173-
"""Create mapping between unique categorical values
174-
and integer identifiers
158+
"""
159+
Create mapping between unique categorical values and integer ids.
160+
161+
Parameters
175162
----------
176163
data: iterable
177164
sequence of string values
178165
"""
179166
self._mapping = OrderedDict()
180-
self._counter = itertools.count(start=0)
167+
self._counter = itertools.count()
181168
if data is not None:
182169
self.update(data)
183170

@@ -197,7 +184,7 @@ def update(self, data):
197184
data = np.atleast_1d(np.array(data, dtype=object))
198185

199186
for val in OrderedDict.fromkeys(data):
200-
if not isinstance(val, VALID_TYPES):
187+
if not isinstance(val, (str, bytes)):
201188
raise TypeError("{val!r} is not a string".format(val=val))
202189
if val not in self._mapping:
203190
self._mapping[val] = next(self._counter)
@@ -206,6 +193,5 @@ def update(self, data):
206193
# Connects the convertor to matplotlib
207194
units.registry[str] = StrCategoryConverter()
208195
units.registry[np.str_] = StrCategoryConverter()
209-
units.registry[six.text_type] = StrCategoryConverter()
210196
units.registry[bytes] = StrCategoryConverter()
211197
units.registry[np.bytes_] = StrCategoryConverter()

0 commit comments

Comments
 (0)