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 5e04ca4

Browse filesBrowse files
committed
Merge remote-tracking branch 'matplotlib/v2.x'
Conflicts: lib/matplotlib/backends/backend_pdf.py conflicts due moving to context manager + six.next -> next Resolved by manually merging changes (use `next` in a context manager) lib/matplotlib/tests/test_backend_svg.py White space conflicts lib/mpl_toolkits/tests/test_axes_grid1.py conflicts in changes to import statements
2 parents c210b0d + 4b66272 commit 5e04ca4
Copy full SHA for 5e04ca4

File tree

Expand file treeCollapse file tree

13 files changed

+170
-55
lines changed
Filter options
Expand file treeCollapse file tree

13 files changed

+170
-55
lines changed

‎examples/axes_grid/simple_axisline4.py

Copy file name to clipboardExpand all lines: examples/axes_grid/simple_axisline4.py
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"])
1414

1515
ax2.axis["right"].major_ticklabels.set_visible(False)
16+
ax2.axis["top"].major_ticklabels.set_visible(True)
1617

1718
plt.draw()
1819
plt.show()

‎lib/matplotlib/axes/_axes.py

Copy file name to clipboardExpand all lines: lib/matplotlib/axes/_axes.py
+55-44Lines changed: 55 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2338,11 +2338,11 @@ def broken_barh(self, xranges, yrange, **kwargs):
23382338
"""
23392339
# process the unit information
23402340
if len(xranges):
2341-
xdata = six.next(iter(xranges))
2341+
xdata = cbook.safe_first_element(xranges)
23422342
else:
23432343
xdata = None
23442344
if len(yrange):
2345-
ydata = six.next(iter(yrange))
2345+
ydata = cbook.safe_first_element(yrange)
23462346
else:
23472347
ydata = None
23482348
self._process_unit_info(xdata=xdata,
@@ -3024,7 +3024,7 @@ def xywhere(xs, ys, mask):
30243024

30253025
if ecolor is None:
30263026
if l0 is None and 'color' in self._get_lines._prop_keys:
3027-
ecolor = six.next(self._get_lines.prop_cycler)['color']
3027+
ecolor = next(self._get_lines.prop_cycler)['color']
30283028
else:
30293029
ecolor = l0.get_color()
30303030

@@ -5904,6 +5904,41 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None,
59045904
.. plot:: mpl_examples/statistics/histogram_demo_features.py
59055905
59065906
"""
5907+
def _normalize_input(inp, ename='input'):
5908+
"""Normalize 1 or 2d input into list of np.ndarray or
5909+
a single 2D np.ndarray.
5910+
5911+
Parameters
5912+
----------
5913+
inp : iterable
5914+
ename : str, optional
5915+
Name to use in ValueError if `inp` can not be normalized
5916+
5917+
"""
5918+
if (isinstance(x, np.ndarray) or
5919+
not iterable(cbook.safe_first_element(inp))):
5920+
# TODO: support masked arrays;
5921+
inp = np.asarray(inp)
5922+
if inp.ndim == 2:
5923+
# 2-D input with columns as datasets; switch to rows
5924+
inp = inp.T
5925+
elif inp.ndim == 1:
5926+
# new view, single row
5927+
inp = inp.reshape(1, inp.shape[0])
5928+
else:
5929+
raise ValueError(
5930+
"{ename} must be 1D or 2D".format(ename=ename))
5931+
if inp.shape[1] < inp.shape[0]:
5932+
warnings.warn(
5933+
'2D hist input should be nsamples x nvariables;\n '
5934+
'this looks transposed '
5935+
'(shape is %d x %d)' % inp.shape[::-1])
5936+
else:
5937+
# multiple hist with data of different length
5938+
inp = [np.asarray(xi) for xi in inp]
5939+
5940+
return inp
5941+
59075942
if not self._hold:
59085943
self.cla()
59095944

@@ -5950,58 +5985,34 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None,
59505985
input_empty = len(flat) == 0
59515986

59525987
# Massage 'x' for processing.
5953-
# NOTE: Be sure any changes here is also done below to 'weights'
59545988
if input_empty:
59555989
x = np.array([[]])
5956-
elif isinstance(x, np.ndarray) or not iterable(x[0]):
5957-
# TODO: support masked arrays;
5958-
x = np.asarray(x)
5959-
if x.ndim == 2:
5960-
x = x.T # 2-D input with columns as datasets; switch to rows
5961-
elif x.ndim == 1:
5962-
x = x.reshape(1, x.shape[0]) # new view, single row
5963-
else:
5964-
raise ValueError("x must be 1D or 2D")
5965-
if x.shape[1] < x.shape[0]:
5966-
warnings.warn(
5967-
'2D hist input should be nsamples x nvariables;\n '
5968-
'this looks transposed (shape is %d x %d)' % x.shape[::-1])
59695990
else:
5970-
# multiple hist with data of different length
5971-
x = [np.asarray(xi) for xi in x]
5972-
5991+
x = _normalize_input(x, 'x')
59735992
nx = len(x) # number of datasets
59745993

5994+
# We need to do to 'weights' what was done to 'x'
5995+
if weights is not None:
5996+
w = _normalize_input(weights, 'weights')
5997+
else:
5998+
w = [None]*nx
5999+
6000+
if len(w) != nx:
6001+
raise ValueError('weights should have the same shape as x')
6002+
6003+
for xi, wi in zip(x, w):
6004+
if wi is not None and len(wi) != len(xi):
6005+
raise ValueError(
6006+
'weights should have the same shape as x')
6007+
59756008
if color is None and 'color' in self._get_lines._prop_keys:
5976-
color = [six.next(self._get_lines.prop_cycler)['color']
6009+
color = [next(self._get_lines.prop_cycler)['color']
59776010
for i in xrange(nx)]
59786011
else:
59796012
color = mcolors.colorConverter.to_rgba_array(color)
59806013
if len(color) != nx:
59816014
raise ValueError("color kwarg must have one color per dataset")
59826015

5983-
# We need to do to 'weights' what was done to 'x'
5984-
if weights is not None:
5985-
if isinstance(weights, np.ndarray) or not iterable(weights[0]):
5986-
w = np.array(weights)
5987-
if w.ndim == 2:
5988-
w = w.T
5989-
elif w.ndim == 1:
5990-
w.shape = (1, w.shape[0])
5991-
else:
5992-
raise ValueError("weights must be 1D or 2D")
5993-
else:
5994-
w = [np.asarray(wi) for wi in weights]
5995-
5996-
if len(w) != nx:
5997-
raise ValueError('weights should have the same shape as x')
5998-
for i in xrange(nx):
5999-
if len(w[i]) != len(x[i]):
6000-
raise ValueError(
6001-
'weights should have the same shape as x')
6002-
else:
6003-
w = [None]*nx
6004-
60056016
# Save the datalimits for the same reason:
60066017
_saved_bounds = self.dataLim.bounds
60076018

@@ -6017,7 +6028,7 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None,
60176028
xmax = max(xmax, xi.max())
60186029
bin_range = (xmin, xmax)
60196030

6020-
#hist_kwargs = dict(range=range, normed=bool(normed))
6031+
# hist_kwargs = dict(range=range, normed=bool(normed))
60216032
# We will handle the normed kwarg within mpl until we
60226033
# get to the point of requiring numpy >= 1.5.
60236034
hist_kwargs = dict(range=bin_range)

‎lib/matplotlib/axes/_base.py

Copy file name to clipboardExpand all lines: lib/matplotlib/axes/_base.py
+2-1Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import matplotlib.image as mimage
3535
from matplotlib.offsetbox import OffsetBox
3636
from matplotlib.artist import allow_rasterization
37+
3738
from matplotlib.rcsetup import cycler
3839

3940
rcParams = matplotlib.rcParams
@@ -1108,7 +1109,7 @@ def set_prop_cycle(self, *args, **kwargs):
11081109
Can also be `None` to reset to the cycle defined by the
11091110
current style.
11101111
1111-
label : name
1112+
label : str
11121113
The property key. Must be a valid `Artist` property.
11131114
For example, 'color' or 'linestyle'. Aliases are allowed,
11141115
such as 'c' for 'color' and 'lw' for 'linewidth'.

‎lib/matplotlib/backends/backend_pdf.py

Copy file name to clipboardExpand all lines: lib/matplotlib/backends/backend_pdf.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1843,7 +1843,7 @@ def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None):
18431843
fontsize = prop.get_size_in_points()
18441844
dvifile = texmanager.make_dvi(s, fontsize)
18451845
with dviread.Dvi(dvifile, 72) as dvi:
1846-
page = six.next(iter(dvi))
1846+
page = next(iter(dvi))
18471847

18481848
# Gather font information and do some setup for combining
18491849
# characters into strings. The variable seq will contain a

‎lib/matplotlib/cbook.py

Copy file name to clipboardExpand all lines: lib/matplotlib/cbook.py
+8Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from matplotlib.externals import six
1313
from matplotlib.externals.six.moves import xrange, zip
1414
from itertools import repeat
15+
import collections
1516

1617
import datetime
1718
import errno
@@ -2420,6 +2421,13 @@ def index_of(y):
24202421
return np.arange(y.shape[0], dtype=float), y
24212422

24222423

2424+
def safe_first_element(obj):
2425+
if isinstance(obj, collections.Iterator):
2426+
raise RuntimeError("matplotlib does not support generators "
2427+
"as input")
2428+
return next(iter(obj))
2429+
2430+
24232431
def get_label(y, default_name):
24242432
try:
24252433
return y.name

‎lib/matplotlib/dates.py

Copy file name to clipboardExpand all lines: lib/matplotlib/dates.py
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1561,8 +1561,8 @@ def default_units(x, axis):
15611561
x = x.ravel()
15621562

15631563
try:
1564-
x = x[0]
1565-
except (TypeError, IndexError):
1564+
x = cbook.safe_first_element(x)
1565+
except (TypeError, StopIteration):
15661566
pass
15671567

15681568
try:

‎lib/matplotlib/tests/test_axes.py

Copy file name to clipboardExpand all lines: lib/matplotlib/tests/test_axes.py
+31Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import io
88

99
from nose.tools import assert_equal, assert_raises, assert_false, assert_true
10+
from nose.plugins.skip import SkipTest
1011

1112
import datetime
1213

@@ -4292,6 +4293,36 @@ def test_broken_barh_empty():
42924293
ax.broken_barh([], (.1, .5))
42934294

42944295

4296+
@cleanup
4297+
def test_pandas_indexing_dates():
4298+
try:
4299+
import pandas as pd
4300+
except ImportError:
4301+
raise SkipTest("Pandas not installed")
4302+
4303+
dates = np.arange('2005-02', '2005-03', dtype='datetime64[D]')
4304+
values = np.sin(np.array(range(len(dates))))
4305+
df = pd.DataFrame({'dates': dates, 'values': values})
4306+
4307+
ax = plt.gca()
4308+
4309+
without_zero_index = df[np.array(df.index) % 2 == 1].copy()
4310+
ax.plot('dates', 'values', data=without_zero_index)
4311+
4312+
4313+
@cleanup
4314+
def test_pandas_indexing_hist():
4315+
try:
4316+
import pandas as pd
4317+
except ImportError:
4318+
raise SkipTest("Pandas not installed")
4319+
4320+
ser_1 = pd.Series(data=[1, 2, 2, 3, 3, 4, 4, 4, 4, 5])
4321+
ser_2 = ser_1.iloc[1:]
4322+
fig, axes = plt.subplots()
4323+
axes.hist(ser_2)
4324+
4325+
42954326
if __name__ == '__main__':
42964327
import nose
42974328
import sys

‎lib/matplotlib/tests/test_backend_svg.py

Copy file name to clipboardExpand all lines: lib/matplotlib/tests/test_backend_svg.py
+7-1Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,12 @@
99

1010
import matplotlib.pyplot as plt
1111
from matplotlib.testing.decorators import cleanup
12-
from matplotlib.testing.decorators import image_comparison
12+
from matplotlib.testing.decorators import image_comparison, knownfailureif
13+
import matplotlib
14+
15+
needs_tex = knownfailureif(
16+
not matplotlib.checkdep_tex(),
17+
"This test needs a TeX installation")
1318

1419

1520
@cleanup
@@ -173,6 +178,7 @@ def test_determinism_notex():
173178

174179

175180
@cleanup
181+
@needs_tex
176182
def test_determinism_tex():
177183
# unique filename to allow for parallel testing
178184
_test_determinism('determinism_tex.svg', usetex=True)

‎lib/mpl_toolkits/axes_grid1/anchored_artists.py

Copy file name to clipboardExpand all lines: lib/mpl_toolkits/axes_grid1/anchored_artists.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ def __init__(self, transform, size, label, loc,
335335
"""
336336
self.size_bar = AuxTransformBox(transform)
337337
self.size_bar.add_artist(Rectangle((0, 0), size, size_vertical,
338-
fill=True, facecolor=color,
338+
fill=False, facecolor=color,
339339
edgecolor=color))
340340

341341
if fontproperties is None and 'prop' in kwargs:

‎lib/mpl_toolkits/axes_grid1/inset_locator.py

Copy file name to clipboardExpand all lines: lib/mpl_toolkits/axes_grid1/inset_locator.py
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ def __init__(self, bbox1, bbox2, loc1, loc2=None, **kwargs):
312312
raise ValueError("transform should not be set")
313313

314314
kwargs["transform"] = IdentityTransform()
315-
Patch.__init__(self, **kwargs)
315+
Patch.__init__(self, fill=False, **kwargs)
316316
self.bbox1 = bbox1
317317
self.bbox2 = bbox2
318318
self.loc1 = loc1
@@ -582,7 +582,7 @@ def mark_inset(parent_axes, inset_axes, loc1, loc2, **kwargs):
582582
"""
583583
rect = TransformedBbox(inset_axes.viewLim, parent_axes.transData)
584584

585-
pp = BboxPatch(rect, **kwargs)
585+
pp = BboxPatch(rect, fill=False, **kwargs)
586586
parent_axes.add_patch(pp)
587587

588588
p1 = BboxConnector(inset_axes.bbox, rect, loc1=loc1, **kwargs)
Loading

‎lib/mpl_toolkits/tests/test_axes_grid1.py

Copy file name to clipboardExpand all lines: lib/mpl_toolkits/tests/test_axes_grid1.py
+56-1Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,13 @@
66
import matplotlib
77
import matplotlib.pyplot as plt
88
from matplotlib.testing.decorators import image_comparison, cleanup
9-
from mpl_toolkits.axes_grid1 import make_axes_locatable, host_subplot, AxesGrid
9+
10+
from mpl_toolkits.axes_grid1 import host_subplot
11+
from mpl_toolkits.axes_grid1 import make_axes_locatable
12+
from mpl_toolkits.axes_grid1 import AxesGrid
13+
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset
14+
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
15+
1016
from matplotlib.colors import LogNorm
1117
from itertools import product
1218

@@ -101,6 +107,55 @@ def test_axesgrid_colorbar_log_smoketest():
101107
grid.cbar_axes[0].colorbar(im)
102108

103109

110+
@image_comparison(
111+
baseline_images=['inset_locator'], style='default', extensions=['png'],
112+
remove_text=True)
113+
def test_inset_locator():
114+
def get_demo_image():
115+
from matplotlib.cbook import get_sample_data
116+
import numpy as np
117+
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
118+
z = np.load(f)
119+
# z is a numpy array of 15x15
120+
return z, (-3, 4, -4, 3)
121+
122+
fig, ax = plt.subplots(figsize=[5, 4])
123+
124+
# prepare the demo image
125+
Z, extent = get_demo_image()
126+
Z2 = np.zeros([150, 150], dtype="d")
127+
ny, nx = Z.shape
128+
Z2[30:30 + ny, 30:30 + nx] = Z
129+
130+
# extent = [-3, 4, -4, 3]
131+
ax.imshow(Z2, extent=extent, interpolation="nearest",
132+
origin="lower")
133+
134+
axins = zoomed_inset_axes(ax, 6, loc=1) # zoom = 6
135+
axins.imshow(Z2, extent=extent, interpolation="nearest",
136+
origin="lower")
137+
138+
# sub region of the original image
139+
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
140+
axins.set_xlim(x1, x2)
141+
axins.set_ylim(y1, y2)
142+
143+
plt.xticks(visible=False)
144+
plt.yticks(visible=False)
145+
146+
# draw a bbox of the region of the inset axes in the parent axes and
147+
# connecting lines between the bbox and the inset axes area
148+
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
149+
150+
asb = AnchoredSizeBar(ax.transData,
151+
0.5,
152+
'0.5',
153+
loc=8,
154+
pad=0.1, borderpad=0.5, sep=5,
155+
frameon=False)
156+
ax.add_artist(asb)
157+
158+
104159
if __name__ == '__main__':
105160
import nose
106161
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)

0 commit comments

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