diff --git a/examples/api/affine_image.py b/examples/api/affine_image.py index 9ce1cff0563a..67606d932daa 100644 --- a/examples/api/affine_image.py +++ b/examples/api/affine_image.py @@ -9,7 +9,6 @@ """ import numpy as np -import matplotlib.mlab as mlab import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms @@ -18,9 +17,9 @@ def get_image(): delta = 0.25 x = y = np.arange(-3.0, 3.0, delta) X, Y = np.meshgrid(x, y) - Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) - Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) - Z = Z2 - Z1 # difference of Gaussians + Z1 = np.exp(-X**2 - Y**2) + Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) + Z = (Z1 - Z2) return Z diff --git a/examples/frontpage/contour.py b/examples/frontpage/contour.py index 9622cc015088..ddb0721c1203 100644 --- a/examples/frontpage/contour.py +++ b/examples/frontpage/contour.py @@ -8,7 +8,7 @@ import matplotlib.pyplot as plt import numpy as np -from matplotlib import mlab, cm +from matplotlib import cm extent = (-3, 3, -3, 3) @@ -16,19 +16,19 @@ x = np.arange(-3.0, 4.001, delta) y = np.arange(-4.0, 3.001, delta) X, Y = np.meshgrid(x, y) -Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, -0.5) -Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -Z = (Z1 - Z2) * 10 +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = Z1 - Z2 -levels = np.linspace(-2.0, 1.601, 40) norm = cm.colors.Normalize(vmax=abs(Z).max(), vmin=-abs(Z).max()) fig, ax = plt.subplots() cset1 = ax.contourf( - X, Y, Z, levels, + X, Y, Z, 40, norm=norm) -ax.set_xlim(-3, 3) -ax.set_ylim(-3, 3) +ax.set_xlim(-2, 2) +ax.set_ylim(-2, 2) ax.set_xticks([]) ax.set_yticks([]) fig.savefig("contour_frontpage.png", dpi=25) # results in 160x120 px image +plt.show() diff --git a/examples/images_contours_and_fields/contour_demo.py b/examples/images_contours_and_fields/contour_demo.py index 95a63ebd690c..4689d3507f64 100644 --- a/examples/images_contours_and_fields/contour_demo.py +++ b/examples/images_contours_and_fields/contour_demo.py @@ -11,7 +11,6 @@ import matplotlib import numpy as np import matplotlib.cm as cm -import matplotlib.mlab as mlab import matplotlib.pyplot as plt matplotlib.rcParams['xtick.direction'] = 'out' @@ -21,10 +20,9 @@ x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) -Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -# difference of Gaussians -Z = 10.0 * (Z2 - Z1) +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 ############################################################################### # Create a simple contour plot with labels using default colors. The diff --git a/examples/images_contours_and_fields/contour_image.py b/examples/images_contours_and_fields/contour_image.py index 1fc1bbc95b05..3f0f007dcca4 100644 --- a/examples/images_contours_and_fields/contour_image.py +++ b/examples/images_contours_and_fields/contour_image.py @@ -13,7 +13,7 @@ """ import matplotlib.pyplot as plt import numpy as np -from matplotlib import mlab, cm +from matplotlib import cm # Default delta is large because that makes it fast, and it illustrates # the correct registration between image and contours. @@ -24,9 +24,9 @@ x = np.arange(-3.0, 4.001, delta) y = np.arange(-4.0, 3.001, delta) X, Y = np.meshgrid(x, y) -Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -Z = (Z1 - Z2) * 10 +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 # Boost the upper limit to avoid truncation errors. levels = np.arange(-2.0, 1.601, 0.4) diff --git a/examples/images_contours_and_fields/contour_label_demo.py b/examples/images_contours_and_fields/contour_label_demo.py index 3b1d5b3188cf..7140b9b13a44 100644 --- a/examples/images_contours_and_fields/contour_label_demo.py +++ b/examples/images_contours_and_fields/contour_label_demo.py @@ -11,7 +11,6 @@ import matplotlib import numpy as np import matplotlib.cm as cm -import matplotlib.mlab as mlab import matplotlib.ticker as ticker import matplotlib.pyplot as plt @@ -25,10 +24,9 @@ x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) -Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -# difference of Gaussians -Z = 10.0 * (Z2 - Z1) +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 ############################################################################### # Make contour labels using creative float classes diff --git a/examples/images_contours_and_fields/contourf_demo.py b/examples/images_contours_and_fields/contourf_demo.py index e719a2655d35..41523cfdf7c2 100644 --- a/examples/images_contours_and_fields/contourf_demo.py +++ b/examples/images_contours_and_fields/contourf_demo.py @@ -14,9 +14,9 @@ x = y = np.arange(-3.0, 3.01, delta) X, Y = np.meshgrid(x, y) -Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -Z = 10 * (Z1 - Z2) +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 nr, nc = Z.shape diff --git a/examples/images_contours_and_fields/contourf_log.py b/examples/images_contours_and_fields/contourf_log.py index 53d56d775cca..96ee55c51215 100644 --- a/examples/images_contours_and_fields/contourf_log.py +++ b/examples/images_contours_and_fields/contourf_log.py @@ -10,7 +10,6 @@ import numpy as np from numpy import ma from matplotlib import ticker, cm -from matplotlib.mlab import bivariate_normal N = 100 x = np.linspace(-3.0, 3.0, N) @@ -18,11 +17,12 @@ X, Y = np.meshgrid(x, y) -# A low hump with a spike coming out of the top right. +# A low hump with a spike coming out. # Needs to have z/colour axis on a log scale so we see both hump and spike. # linear scale only shows the spike. -z = (bivariate_normal(X, Y, 0.1, 0.2, 1.0, 1.0) - + 0.1 * bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)) +Z1 = np.exp(-(X)**2 - (Y)**2) +Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) +z = Z1 + 50 * Z2 # Put in some negative values (lower left corner) to cause trouble with logs: z[:5, :5] = -1 @@ -39,10 +39,10 @@ # Alternatively, you can manually set the levels # and the norm: -#lev_exp = np.arange(np.floor(np.log10(z.min())-1), +# lev_exp = np.arange(np.floor(np.log10(z.min())-1), # np.ceil(np.log10(z.max())+1)) -#levs = np.power(10, lev_exp) -#cs = P.contourf(X, Y, z, levs, norm=colors.LogNorm()) +# levs = np.power(10, lev_exp) +# cs = P.contourf(X, Y, z, levs, norm=colors.LogNorm()) # The 'extend' kwarg does not work yet with a log scale. diff --git a/examples/images_contours_and_fields/griddata_demo.py b/examples/images_contours_and_fields/griddata_demo.py deleted file mode 100644 index 540e5119256a..000000000000 --- a/examples/images_contours_and_fields/griddata_demo.py +++ /dev/null @@ -1,34 +0,0 @@ -""" -============= -Griddata Demo -============= - -Example showing plotting of non uniform data points in the form of grid. -""" -from matplotlib.mlab import griddata -import matplotlib.pyplot as plt -import numpy as np - -# make up data. -random_state = np.random.RandomState(19680801) - -npts = 200 -x = random_state.uniform(-2, 2, npts) -y = random_state.uniform(-2, 2, npts) -z = x*np.exp(-x**2 - y**2) -# define grid. -xi = np.linspace(-2.1, 2.1, 100) -yi = np.linspace(-2.1, 2.1, 200) -# grid the data. -zi = griddata(x, y, z, xi, yi, interp='linear') -# contour the gridded data, plotting dots at the nonuniform data points. -CS = plt.contour(xi, yi, zi, 15, linewidths=0.5, colors='k') -CS = plt.contourf(xi, yi, zi, 15, - vmax=abs(zi).max(), vmin=-abs(zi).max()) -plt.colorbar() # draw colorbar -# plot data points. -plt.scatter(x, y, marker='o', s=5, zorder=10) -plt.xlim(-2, 2) -plt.ylim(-2, 2) -plt.title('griddata test (%d points)' % npts) -plt.show() diff --git a/examples/images_contours_and_fields/image_demo.py b/examples/images_contours_and_fields/image_demo.py index 6400f6391109..b6d8eaed9ffe 100644 --- a/examples/images_contours_and_fields/image_demo.py +++ b/examples/images_contours_and_fields/image_demo.py @@ -14,7 +14,6 @@ import numpy as np import matplotlib.cm as cm -import matplotlib.mlab as mlab import matplotlib.pyplot as plt import matplotlib.cbook as cbook from matplotlib.path import Path @@ -26,9 +25,9 @@ delta = 0.025 x = y = np.arange(-3.0, 3.0, delta) X, Y = np.meshgrid(x, y) -Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -Z = Z2 - Z1 # difference of Gaussians +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 im = plt.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn, origin='lower', extent=[-3, 3, -3, 3], @@ -156,9 +155,9 @@ delta = 0.025 x = y = np.arange(-3.0, 3.0, delta) X, Y = np.meshgrid(x, y) -Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -Z = Z2 - Z1 # difference of Gaussians +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 path = Path([[0, 1], [1, 0], [0, -1], [-1, 0], [0, 1]]) patch = PathPatch(path, facecolor='none') diff --git a/examples/images_contours_and_fields/image_masked.py b/examples/images_contours_and_fields/image_masked.py index f94c5be1cb15..029201ef1a1b 100644 --- a/examples/images_contours_and_fields/image_masked.py +++ b/examples/images_contours_and_fields/image_masked.py @@ -13,7 +13,6 @@ import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors -import matplotlib.mlab as mlab # compute some interesting data x0, x1 = -5, 5 @@ -21,9 +20,9 @@ x = np.linspace(x0, x1, 500) y = np.linspace(y0, y1, 500) X, Y = np.meshgrid(x, y) -Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -Z = 10*(Z2 - Z1) # difference of Gaussians +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 # Set up a colormap: # use copy so that we do not mutate the global colormap instance diff --git a/examples/images_contours_and_fields/pcolor_demo.py b/examples/images_contours_and_fields/pcolor_demo.py index 5a055c1d9f33..37927f241318 100644 --- a/examples/images_contours_and_fields/pcolor_demo.py +++ b/examples/images_contours_and_fields/pcolor_demo.py @@ -11,8 +11,6 @@ import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import LogNorm -from matplotlib.mlab import bivariate_normal - ############################################################################### # A simple pcolor demo @@ -91,19 +89,20 @@ N = 100 X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] -# A low hump with a spike coming out of the top right. +# A low hump with a spike coming out. # Needs to have z/colour axis on a log scale so we see both hump and spike. # linear scale only shows the spike. -Z1 = (bivariate_normal(X, Y, 0.1, 0.2, 1.0, 1.0) + - 0.1 * bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)) +Z1 = np.exp(-(X)**2 - (Y)**2) +Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) +Z = Z1 + 50 * Z2 fig, (ax0, ax1) = plt.subplots(2, 1) -c = ax0.pcolor(X, Y, Z1, - norm=LogNorm(vmin=Z1.min(), vmax=Z1.max()), cmap='PuBu_r') +c = ax0.pcolor(X, Y, Z, + norm=LogNorm(vmin=Z.min(), vmax=Z.max()), cmap='PuBu_r') fig.colorbar(c, ax=ax0) -c = ax1.pcolor(X, Y, Z1, cmap='PuBu_r') +c = ax1.pcolor(X, Y, Z, cmap='PuBu_r') fig.colorbar(c, ax=ax1) plt.show() diff --git a/examples/images_contours_and_fields/tricontour_vs_griddata.py b/examples/images_contours_and_fields/tricontour_vs_griddata.py deleted file mode 100644 index 42d1065005d0..000000000000 --- a/examples/images_contours_and_fields/tricontour_vs_griddata.py +++ /dev/null @@ -1,56 +0,0 @@ -""" -====================== -Tricontour Vs Griddata -====================== - -Comparison of griddata and tricontour for an unstructured triangular grid. -""" -from __future__ import print_function -import matplotlib.pyplot as plt -import matplotlib.tri as tri -import numpy as np -import matplotlib.mlab as mlab -import time - -np.random.seed(0) -npts = 200 -ngridx = 100 -ngridy = 200 -x = np.random.uniform(-2, 2, npts) -y = np.random.uniform(-2, 2, npts) -z = x * np.exp(-x**2 - y**2) - -# griddata and contour. -start = time.clock() -plt.subplot(211) -xi = np.linspace(-2.1, 2.1, ngridx) -yi = np.linspace(-2.1, 2.1, ngridy) -zi = mlab.griddata(x, y, z, xi, yi, interp='linear') -plt.contour(xi, yi, zi, 15, linewidths=0.5, colors='k') -plt.contourf(xi, yi, zi, 15, - norm=plt.Normalize(vmax=abs(zi).max(), vmin=-abs(zi).max())) -plt.colorbar() # draw colorbar -plt.plot(x, y, 'ko', ms=3) -plt.xlim(-2, 2) -plt.ylim(-2, 2) -plt.title('griddata and contour (%d points, %d grid points)' % - (npts, ngridx * ngridy)) -print('griddata and contour: %f seconds' % (time.clock() - start)) - -# tricontour. -start = time.clock() -plt.subplot(212) -triang = tri.Triangulation(x, y) -plt.tricontour(x, y, z, 15, linewidths=0.5, colors='k') -plt.tricontourf(x, y, z, 15, - norm=plt.Normalize(vmax=abs(zi).max(), vmin=-abs(zi).max())) -plt.colorbar() -plt.plot(x, y, 'ko', ms=3) -plt.xlim(-2, 2) -plt.ylim(-2, 2) -plt.title('tricontour (%d points)' % npts) -print('tricontour: %f seconds' % (time.clock() - start)) - -plt.subplots_adjust(hspace=0.5) - -plt.show() diff --git a/examples/lines_bars_and_markers/interp_demo.py b/examples/lines_bars_and_markers/interp_demo.py index 4fcab49f4b94..ad85dfdead94 100644 --- a/examples/lines_bars_and_markers/interp_demo.py +++ b/examples/lines_bars_and_markers/interp_demo.py @@ -6,13 +6,12 @@ """ import matplotlib.pyplot as plt import numpy as np -from matplotlib.mlab import stineman_interp -x = np.linspace(0, 2*np.pi, 20) +x = np.linspace(0, 2 * np.pi, 20) y = np.sin(x) yp = None xi = np.linspace(x[0], x[-1], 100) -yi = stineman_interp(xi, x, y, yp) +yi = np.interp(xi, x, y, yp) fig, ax = plt.subplots() ax.plot(x, y, 'o', xi, yi, '.') diff --git a/examples/misc/demo_agg_filter.py b/examples/misc/demo_agg_filter.py index b058e242e17d..1c00c92e4265 100644 --- a/examples/misc/demo_agg_filter.py +++ b/examples/misc/demo_agg_filter.py @@ -8,7 +8,6 @@ import numpy as np import matplotlib.cm as cm -import matplotlib.mlab as mlab import matplotlib.transforms as mtransforms from matplotlib.colors import LightSource from matplotlib.artist import Artist @@ -187,10 +186,9 @@ def filtered_text(ax): x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) - Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) - Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) - # difference of Gaussians - Z = 10.0 * (Z2 - Z1) + Z1 = np.exp(-X**2 - Y**2) + Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) + Z = (Z1 - Z2) * 2 # draw im = ax.imshow(Z, interpolation='bilinear', origin='lower', diff --git a/examples/misc/hyperlinks_sgskip.py b/examples/misc/hyperlinks_sgskip.py index 6f1b1cea0dab..5298d45cdc0e 100644 --- a/examples/misc/hyperlinks_sgskip.py +++ b/examples/misc/hyperlinks_sgskip.py @@ -12,7 +12,6 @@ import numpy as np import matplotlib.cm as cm -import matplotlib.mlab as mlab import matplotlib.pyplot as plt ############################################################################### @@ -28,9 +27,9 @@ delta = 0.025 x = y = np.arange(-3.0, 3.0, delta) X, Y = np.meshgrid(x, y) -Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -Z = Z2 - Z1 # difference of Gaussians +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 im = plt.imshow(Z, interpolation='bilinear', cmap=cm.gray, origin='lower', extent=[-3, 3, -3, 3]) diff --git a/examples/misc/rec_groupby_demo.py b/examples/misc/rec_groupby_demo.py deleted file mode 100644 index 9cf108a3acde..000000000000 --- a/examples/misc/rec_groupby_demo.py +++ /dev/null @@ -1,71 +0,0 @@ -""" -================ -Rec Groupby Demo -================ - -""" -from __future__ import print_function -import numpy as np -import matplotlib.mlab as mlab -import matplotlib.cbook as cbook - -datafile = cbook.get_sample_data('msft.csv', asfileobj=False) -print('loading', datafile) -r = mlab.csv2rec(datafile) -r.sort() - - -def daily_return(prices): - 'an array of daily returns from price array' - g = np.zeros_like(prices) - g[1:] = (prices[1:] - prices[:-1])/prices[:-1] - return g - - -def volume_code(volume): - 'code the continuous volume data categorically' - ind = np.searchsorted([1e5, 1e6, 5e6, 10e6, 1e7], volume) - return ind - -# a list of (dtype_name, summary_function, output_dtype_name). -# rec_summarize will call on each function on the indicated recarray -# attribute, and the result assigned to output name in the return -# record array. -summaryfuncs = ( - ('date', lambda x: [thisdate.year for thisdate in x], 'years'), - ('date', lambda x: [thisdate.month for thisdate in x], 'months'), - ('date', lambda x: [thisdate.weekday() for thisdate in x], 'weekday'), - ('adj_close', daily_return, 'dreturn'), - ('volume', volume_code, 'volcode'), - ) - -rsum = mlab.rec_summarize(r, summaryfuncs) - -# stats is a list of (dtype_name, function, output_dtype_name). -# rec_groupby will summarize the attribute identified by the -# dtype_name over the groups in the groupby list, and assign the -# result to the output_dtype_name -stats = ( - ('dreturn', len, 'rcnt'), - ('dreturn', np.mean, 'rmean'), - ('dreturn', np.median, 'rmedian'), - ('dreturn', np.std, 'rsigma'), - ) - -# you can summarize over a single variable, like years or months -print('summary by years') -ry = mlab.rec_groupby(rsum, ('years',), stats) -print(mlab. rec2txt(ry)) - -print('summary by months') -rm = mlab.rec_groupby(rsum, ('months',), stats) -print(mlab.rec2txt(rm)) - -# or over multiple variables like years and months -print('summary by year and month') -rym = mlab.rec_groupby(rsum, ('years', 'months'), stats) -print(mlab.rec2txt(rym)) - -print('summary by volume') -rv = mlab.rec_groupby(rsum, ('volcode',), stats) -print(mlab.rec2txt(rv)) diff --git a/examples/pyplots/whats_new_98_4_fill_between.py b/examples/pyplots/whats_new_98_4_fill_between.py index 6805d76dd2d1..ed4b7f4ac7d5 100644 --- a/examples/pyplots/whats_new_98_4_fill_between.py +++ b/examples/pyplots/whats_new_98_4_fill_between.py @@ -4,7 +4,6 @@ ============================= """ -import matplotlib.mlab as mlab import matplotlib.pyplot as plt import numpy as np diff --git a/examples/pyplots/whats_new_99_axes_grid.py b/examples/pyplots/whats_new_99_axes_grid.py index c6539f338e88..73c75daf5798 100644 --- a/examples/pyplots/whats_new_99_axes_grid.py +++ b/examples/pyplots/whats_new_99_axes_grid.py @@ -8,32 +8,31 @@ import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.axes_rgb import RGBAxes + def get_demo_image(): # prepare image delta = 0.5 - extent = (-3,4,-4,3) + extent = (-3, 4, -4, 3) x = np.arange(-3.0, 4.001, delta) y = np.arange(-4.0, 3.001, delta) X, Y = np.meshgrid(x, y) - import matplotlib.mlab as mlab - Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) - Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) - Z = (Z1 - Z2) * 10 + Z1 = np.exp(-X**2 - Y**2) + Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) + Z = (Z1 - Z2) * 2 return Z, extent - def get_rgb(): Z, extent = get_demo_image() - Z[Z<0] = 0. - Z = Z/Z.max() + Z[Z < 0] = 0. + Z = Z / Z.max() - R = Z[:13,:13] - G = Z[2:,2:] - B = Z[:13,2:] + R = Z[:13, :13] + G = Z[2:, 2:] + B = Z[:13, 2:] return R, G, B diff --git a/examples/statistics/hexbin_demo.py b/examples/statistics/hexbin_demo.py index 33446d686549..e04c68458bdd 100644 --- a/examples/statistics/hexbin_demo.py +++ b/examples/statistics/hexbin_demo.py @@ -7,13 +7,12 @@ Hexbin is an axes method or pyplot function that is essentially a pcolor of a 2-D histogram with hexagonal cells. It can be -much more informative than a scatter plot. In the first subplot +much more informative than a scatter plot. In the first plot below, try substituting 'scatter' for 'hexbin'. """ import numpy as np import matplotlib.pyplot as plt -import matplotlib.mlab as mlab # Fixing random state for reproducibility np.random.seed(19680801) @@ -43,53 +42,3 @@ cb.set_label('log10(N)') plt.show() - - -############################################################################### -# Below we'll simulate some 2-D probability distributions, and show how to -# visualize them with Matplotlib. - -delta = 0.025 -x = y = np.arange(-3.0, 3.0, delta) -X, Y = np.meshgrid(x, y) -Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -Z = Z2 - Z1 # difference of Gaussians - -x = X.ravel() -y = Y.ravel() -z = Z.ravel() - -# make some points 20 times more common than others, but same mean -xcond = (-1 < x) & (x < 1) -ycond = (-2 < y) & (y < 0) -cond = xcond & ycond -xnew = x[cond] -ynew = y[cond] -znew = z[cond] -for i in range(20): - x = np.hstack((x, xnew)) - y = np.hstack((y, ynew)) - z = np.hstack((z, znew)) - -xmin = x.min() -xmax = x.max() -ymin = y.min() -ymax = y.max() - -gridsize = 30 - -fig, (ax0, ax1) = plt.subplots(2, 1) - -c = ax0.hexbin(x, y, C=z, gridsize=gridsize, marginals=True, cmap=plt.cm.RdBu, - vmax=abs(z).max(), vmin=-abs(z).max()) -ax0.axis([xmin, xmax, ymin, ymax]) -cb = fig.colorbar(c, ax=ax0) -cb.set_label('mean value') - -c = ax1.hexbin(x, y, gridsize=gridsize, cmap=plt.cm.Blues_r) -ax1.axis([xmin, xmax, ymin, ymax]) -cb = fig.colorbar(c, ax=ax1) -cb.set_label('N observations') - -plt.show() diff --git a/examples/statistics/histogram_cumulative.py b/examples/statistics/histogram_cumulative.py index 3f533ed63d22..b027cb3066da 100644 --- a/examples/statistics/histogram_cumulative.py +++ b/examples/statistics/histogram_cumulative.py @@ -5,8 +5,7 @@ This shows how to plot a cumulative, normalized histogram as a step function in order to visualize the empirical cumulative -distribution function (CDF) of a sample. We also use the ``mlab`` -module to show the theoretical CDF. +distribution function (CDF) of a sample. We also show the theoretical CDF. A couple of other options to the ``hist`` function are demonstrated. Namely, we use the ``normed`` parameter to normalize the histogram and @@ -37,7 +36,6 @@ import numpy as np import matplotlib.pyplot as plt -from matplotlib import mlab np.random.seed(19680801) @@ -53,7 +51,9 @@ cumulative=True, label='Empirical') # Add a line showing the expected distribution. -y = mlab.normpdf(bins, mu, sigma).cumsum() +y = ((1 / (np.sqrt(2 * np.pi) * sigma)) * + np.exp(-0.5 * (1 / sigma * (bins - mu))**2)) +y = y.cumsum() y /= y[-1] ax.plot(bins, y, 'k--', linewidth=1.5, label='Theoretical') diff --git a/examples/statistics/histogram_features.py b/examples/statistics/histogram_features.py index 8c056c49d17c..1199bdb6f74d 100644 --- a/examples/statistics/histogram_features.py +++ b/examples/statistics/histogram_features.py @@ -20,7 +20,6 @@ """ import numpy as np -import matplotlib.mlab as mlab import matplotlib.pyplot as plt np.random.seed(19680801) @@ -35,10 +34,11 @@ fig, ax = plt.subplots() # the histogram of the data -n, bins, patches = ax.hist(x, num_bins, normed=1) +n, bins, patches = ax.hist(x, num_bins, density=1) # add a 'best fit' line -y = mlab.normpdf(bins, mu, sigma) +y = ((1 / (np.sqrt(2 * np.pi) * sigma)) * + np.exp(-0.5 * (1 / sigma * (bins - mu))**2)) ax.plot(bins, y, '--') ax.set_xlabel('Smarts') ax.set_ylabel('Probability density') diff --git a/examples/user_interfaces/histogram_demo_canvasagg_sgskip.py b/examples/user_interfaces/histogram_demo_canvasagg_sgskip.py index 9b42003527e0..1757a1245b5f 100644 --- a/examples/user_interfaces/histogram_demo_canvasagg_sgskip.py +++ b/examples/user_interfaces/histogram_demo_canvasagg_sgskip.py @@ -14,7 +14,6 @@ """ from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure -from matplotlib.mlab import normpdf import numpy as np fig = Figure(figsize=(5, 4), dpi=100) @@ -29,7 +28,8 @@ n, bins, patches = ax.hist(x, 50, density=True) # add a 'best fit' line -y = normpdf(bins, mu, sigma) +y = ((1 / (np.sqrt(2 * np.pi) * sigma)) * + np.exp(-0.5 * (1 / sigma * (bins - mu))**2)) line, = ax.plot(bins, y, 'r--') line.set_linewidth(1) diff --git a/examples/userdemo/colormap_normalizations.py b/examples/userdemo/colormap_normalizations.py index c898a594c3a6..b13d7f213cf5 100644 --- a/examples/userdemo/colormap_normalizations.py +++ b/examples/userdemo/colormap_normalizations.py @@ -9,7 +9,6 @@ import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors -from matplotlib.mlab import bivariate_normal ############################################################################### # Lognorm: Instead of pcolor log10(Z1) you can have colorbars that have @@ -18,21 +17,22 @@ N = 100 X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] -# A low hump with a spike coming out of the top right. Needs to have +# A low hump with a spike coming out of the top. Needs to have # z/colour axis on a log scale so we see both hump and spike. linear # scale only shows the spike. -Z1 = bivariate_normal(X, Y, 0.1, 0.2, 1.0, 1.0) + \ - 0.1 * bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) +Z1 = np.exp(-(X)**2 - (Y)**2) +Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) +Z = Z1 + 50 * Z2 fig, ax = plt.subplots(2, 1) -pcm = ax[0].pcolor(X, Y, Z1, - norm=colors.LogNorm(vmin=Z1.min(), vmax=Z1.max()), +pcm = ax[0].pcolor(X, Y, Z, + norm=colors.LogNorm(vmin=Z.min(), vmax=Z.max()), cmap='PuBu_r') fig.colorbar(pcm, ax=ax[0], extend='max') -pcm = ax[1].pcolor(X, Y, Z1, cmap='PuBu_r') +pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r') fig.colorbar(pcm, ax=ax[1], extend='max') @@ -45,7 +45,7 @@ fig, ax = plt.subplots(2, 1) -pcm = ax[0].pcolormesh(X, Y, Z1, norm=colors.PowerNorm(gamma=1./2.), +pcm = ax[0].pcolormesh(X, Y, Z1, norm=colors.PowerNorm(gamma=1. / 2.), cmap='PuBu_r') fig.colorbar(pcm, ax=ax[0], extend='max') @@ -61,9 +61,9 @@ # Note that colorbar labels do not come out looking very good. X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] -Z1 = (bivariate_normal(X, Y, 1., 1., 1.0, 1.0))**2 \ - - 0.4 * (bivariate_normal(X, Y, 1.0, 1.0, -1.0, 0.0))**2 -Z1 = Z1/0.03 +Z1 = 5 * np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 fig, ax = plt.subplots(2, 1) @@ -83,9 +83,9 @@ # from the positive. X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] -Z1 = (bivariate_normal(X, Y, 1., 1., 1.0, 1.0))**2 \ - - 0.4 * (bivariate_normal(X, Y, 1.0, 1.0, -1.0, 0.0))**2 -Z1 = Z1/0.03 +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 # Example of making your own norm. Also see matplotlib.colors. # From Joe Kington: This one gives two different linear ramps: @@ -101,15 +101,17 @@ def __call__(self, value, clip=None): # simple example... x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] return np.ma.masked_array(np.interp(value, x, y)) + + ##### fig, ax = plt.subplots(2, 1) -pcm = ax[0].pcolormesh(X, Y, Z1, +pcm = ax[0].pcolormesh(X, Y, Z, norm=MidpointNormalize(midpoint=0.), cmap='RdBu_r') fig.colorbar(pcm, ax=ax[0], extend='both') -pcm = ax[1].pcolormesh(X, Y, Z1, cmap='RdBu_r', vmin=-np.max(Z1)) +pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z)) fig.colorbar(pcm, ax=ax[1], extend='both') ############################################################################### @@ -122,7 +124,7 @@ def __call__(self, value, clip=None): # even bounds gives a contour-like effect bounds = np.linspace(-1, 1, 10) norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256) -pcm = ax[0].pcolormesh(X, Y, Z1, +pcm = ax[0].pcolormesh(X, Y, Z, norm=norm, cmap='RdBu_r') fig.colorbar(pcm, ax=ax[0], extend='both', orientation='vertical') @@ -130,10 +132,10 @@ def __call__(self, value, clip=None): # uneven bounds changes the colormapping: bounds = np.array([-0.25, -0.125, 0, 0.5, 1]) norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256) -pcm = ax[1].pcolormesh(X, Y, Z1, norm=norm, cmap='RdBu_r') +pcm = ax[1].pcolormesh(X, Y, Z, norm=norm, cmap='RdBu_r') fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical') -pcm = ax[2].pcolormesh(X, Y, Z1, cmap='RdBu_r', vmin=-np.max(Z1)) +pcm = ax[2].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z1)) fig.colorbar(pcm, ax=ax[2], extend='both', orientation='vertical') plt.show() diff --git a/examples/userdemo/colormap_normalizations_bounds.py b/examples/userdemo/colormap_normalizations_bounds.py index 9e977af020e9..d37113b9dd37 100644 --- a/examples/userdemo/colormap_normalizations_bounds.py +++ b/examples/userdemo/colormap_normalizations_bounds.py @@ -9,13 +9,12 @@ import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors -from matplotlib.mlab import bivariate_normal N = 100 X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] -Z1 = (bivariate_normal(X, Y, 1., 1., 1.0, 1.0))**2 \ - - 0.4 * (bivariate_normal(X, Y, 1.0, 1.0, -1.0, 0.0))**2 -Z1 = Z1/0.03 +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 ''' BoundaryNorm: For this one you provide the boundaries for your colors, @@ -28,7 +27,7 @@ # even bounds gives a contour-like effect bounds = np.linspace(-1, 1, 10) norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256) -pcm = ax[0].pcolormesh(X, Y, Z1, +pcm = ax[0].pcolormesh(X, Y, Z, norm=norm, cmap='RdBu_r') fig.colorbar(pcm, ax=ax[0], extend='both', orientation='vertical') @@ -36,10 +35,10 @@ # uneven bounds changes the colormapping: bounds = np.array([-0.25, -0.125, 0, 0.5, 1]) norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256) -pcm = ax[1].pcolormesh(X, Y, Z1, norm=norm, cmap='RdBu_r') +pcm = ax[1].pcolormesh(X, Y, Z, norm=norm, cmap='RdBu_r') fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical') -pcm = ax[2].pcolormesh(X, Y, Z1, cmap='RdBu_r', vmin=-np.max(Z1)) +pcm = ax[2].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z)) fig.colorbar(pcm, ax=ax[2], extend='both', orientation='vertical') plt.show() diff --git a/examples/userdemo/colormap_normalizations_custom.py b/examples/userdemo/colormap_normalizations_custom.py index ef630a74df90..2eb042f1f4c5 100644 --- a/examples/userdemo/colormap_normalizations_custom.py +++ b/examples/userdemo/colormap_normalizations_custom.py @@ -9,7 +9,6 @@ import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors -from matplotlib.mlab import bivariate_normal N = 100 ''' @@ -18,14 +17,13 @@ from the positive. ''' X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] -Z1 = (bivariate_normal(X, Y, 1., 1., 1.0, 1.0))**2 \ - - 0.4 * (bivariate_normal(X, Y, 1.0, 1.0, -1.0, 0.0))**2 -Z1 = Z1/0.03 +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 + # Example of making your own norm. Also see matplotlib.colors. # From Joe Kington: This one gives two different linear ramps: - - class MidpointNormalize(colors.Normalize): def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): self.midpoint = midpoint @@ -36,15 +34,17 @@ def __call__(self, value, clip=None): # simple example... x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] return np.ma.masked_array(np.interp(value, x, y)) + + ##### fig, ax = plt.subplots(2, 1) -pcm = ax[0].pcolormesh(X, Y, Z1, +pcm = ax[0].pcolormesh(X, Y, Z, norm=MidpointNormalize(midpoint=0.), cmap='RdBu_r') fig.colorbar(pcm, ax=ax[0], extend='both') -pcm = ax[1].pcolormesh(X, Y, Z1, cmap='RdBu_r', vmin=-np.max(Z1)) +pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z)) fig.colorbar(pcm, ax=ax[1], extend='both') plt.show() diff --git a/examples/userdemo/colormap_normalizations_lognorm.py b/examples/userdemo/colormap_normalizations_lognorm.py index 9b3910866149..5b2f7c3668af 100644 --- a/examples/userdemo/colormap_normalizations_lognorm.py +++ b/examples/userdemo/colormap_normalizations_lognorm.py @@ -9,7 +9,6 @@ import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors -from matplotlib.mlab import bivariate_normal ''' Lognorm: Instead of pcolor log10(Z1) you can have colorbars that have @@ -21,17 +20,16 @@ # A low hump with a spike coming out of the top right. Needs to have # z/colour axis on a log scale so we see both hump and spike. linear # scale only shows the spike. -Z1 = bivariate_normal(X, Y, 0.1, 0.2, 1.0, 1.0) + \ - 0.1 * bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) +Z = np.exp(-X**2 - Y**2) fig, ax = plt.subplots(2, 1) -pcm = ax[0].pcolor(X, Y, Z1, - norm=colors.LogNorm(vmin=Z1.min(), vmax=Z1.max()), +pcm = ax[0].pcolor(X, Y, Z, + norm=colors.LogNorm(vmin=Z.min(), vmax=Z.max()), cmap='PuBu_r') fig.colorbar(pcm, ax=ax[0], extend='max') -pcm = ax[1].pcolor(X, Y, Z1, cmap='PuBu_r') +pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r') fig.colorbar(pcm, ax=ax[1], extend='max') plt.show() diff --git a/examples/userdemo/colormap_normalizations_power.py b/examples/userdemo/colormap_normalizations_power.py index 569c8a55cd69..77f052b28ac6 100644 --- a/examples/userdemo/colormap_normalizations_power.py +++ b/examples/userdemo/colormap_normalizations_power.py @@ -9,7 +9,6 @@ import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors -from matplotlib.mlab import bivariate_normal N = 100 X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] diff --git a/examples/userdemo/colormap_normalizations_symlognorm.py b/examples/userdemo/colormap_normalizations_symlognorm.py index b038ca69e96a..780381e43da8 100644 --- a/examples/userdemo/colormap_normalizations_symlognorm.py +++ b/examples/userdemo/colormap_normalizations_symlognorm.py @@ -9,7 +9,6 @@ import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors -from matplotlib.mlab import bivariate_normal """ SymLogNorm: two humps, one negative and one positive, The positive @@ -22,19 +21,19 @@ N = 100 X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] -Z1 = (bivariate_normal(X, Y, 1., 1., 1.0, 1.0)**2 - - 0.4 * bivariate_normal(X, Y, 1.0, 1.0, -1.0, 0.0)**2) -Z1 = Z1 / 0.03 +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 fig, ax = plt.subplots(2, 1) -pcm = ax[0].pcolormesh(X, Y, Z1, +pcm = ax[0].pcolormesh(X, Y, Z, norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03, vmin=-1.0, vmax=1.0), cmap='RdBu_r') fig.colorbar(pcm, ax=ax[0], extend='both') -pcm = ax[1].pcolormesh(X, Y, Z1, cmap='RdBu_r', vmin=-np.max(Z1)) +pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z)) fig.colorbar(pcm, ax=ax[1], extend='both') plt.show() diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 4dedcfc3872f..3abad6b80fef 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -5051,7 +5051,7 @@ def fill_between(self, x, y1, y2=0, where=None, interpolate=False, x, y1, y2 = np.broadcast_arrays(np.atleast_1d(x), y1, y2) polys = [] - for ind0, ind1 in mlab.contiguous_regions(where): + for ind0, ind1 in cbook.contiguous_regions(where): xslice = x[ind0:ind1] y1slice = y1[ind0:ind1] y2slice = y2[ind0:ind1] @@ -5232,7 +5232,7 @@ def fill_betweenx(self, y, x1, x2=0, where=None, y, x1, x2 = np.broadcast_arrays(np.atleast_1d(y), x1, x2) polys = [] - for ind0, ind1 in mlab.contiguous_regions(where): + for ind0, ind1 in cbook.contiguous_regions(where): yslice = y[ind0:ind1] x1slice = x1[ind0:ind1] x2slice = x2[ind0:ind1] diff --git a/lib/matplotlib/cbook/__init__.py b/lib/matplotlib/cbook/__init__.py index 96c33fb3adb2..c90e42e9f641 100644 --- a/lib/matplotlib/cbook/__init__.py +++ b/lib/matplotlib/cbook/__init__.py @@ -1952,6 +1952,7 @@ def unmasked_index_ranges(mask, compressed=True): ls_mapper_r = {v: k for k, v in six.iteritems(ls_mapper)} +@deprecated('2.2') def align_iterators(func, *iterables): """ This generator takes a bunch of iterables that are ordered by func @@ -1996,6 +1997,32 @@ def __call__(self, key): break +def contiguous_regions(mask): + """ + Return a list of (ind0, ind1) such that mask[ind0:ind1].all() is + True and we cover all such regions + """ + mask = np.asarray(mask, dtype=bool) + + if not mask.size: + return [] + + # Find the indices of region changes, and correct offset + idx, = np.nonzero(mask[:-1] != mask[1:]) + idx += 1 + + # List operations are faster for moderately sized arrays + idx = idx.tolist() + + # Add first and/or last index if needed + if mask[0]: + idx = [0] + idx + if mask[-1]: + idx.append(len(mask)) + + return list(zip(idx[::2], idx[1::2])) + + def is_math_text(s): # Did we find an even number of non-escaped dollar signs? # If so, treat is as math text. diff --git a/lib/matplotlib/collections.py b/lib/matplotlib/collections.py index a22f1522957a..f56e6cc2e066 100644 --- a/lib/matplotlib/collections.py +++ b/lib/matplotlib/collections.py @@ -24,7 +24,7 @@ import numpy as np import matplotlib as mpl from . import (_path, artist, cbook, cm, colors as mcolors, docstring, - lines as mlines, mlab, path as mpath, transforms) + lines as mlines, path as mpath, transforms) CIRCLE_AREA_FACTOR = 1.0 / np.sqrt(np.pi) @@ -1040,7 +1040,7 @@ def span_where(x, ymin, ymax, where, **kwargs): passed on to the collection. """ xranges = [] - for ind0, ind1 in mlab.contiguous_regions(where): + for ind0, ind1 in cbook.contiguous_regions(where): xslice = x[ind0:ind1] if not len(xslice): continue diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py index 4c54786dd6a8..d09c3f273f5f 100644 --- a/lib/matplotlib/contour.py +++ b/lib/matplotlib/contour.py @@ -20,7 +20,6 @@ import matplotlib.font_manager as font_manager import matplotlib.text as text import matplotlib.cbook as cbook -import matplotlib.mlab as mlab import matplotlib.mathtext as mathtext import matplotlib.patches as mpatches import matplotlib.texmanager as texmanager @@ -377,7 +376,7 @@ def calc_label_rot_and_inline(self, slc, ind, lw, lc=None, spacing=5): not empty (lc defaults to the empty list if None). *spacing* is the space around the label in pixels to leave empty. - Do both of these tasks at once to avoid calling mlab.path_length + Do both of these tasks at once to avoid calculating path lengths multiple times, which is relatively costly. The method used here involves calculating the path length @@ -392,7 +391,7 @@ def calc_label_rot_and_inline(self, slc, ind, lw, lc=None, spacing=5): hlw = lw / 2.0 # Check if closed and, if so, rotate contour so label is at edge - closed = mlab.is_closed_polygon(slc) + closed = _is_closed_polygon(slc) if closed: slc = np.r_[slc[ind:-1], slc[:ind + 1]] @@ -401,8 +400,10 @@ def calc_label_rot_and_inline(self, slc, ind, lw, lc=None, spacing=5): ind = 0 - # Path length in pixel space - pl = mlab.path_length(slc) + # Calculate path lengths + pl = np.zeros(slc.shape[0], dtype=float) + dx = np.diff(slc, axis=0) + pl[1:] = np.cumsum(np.hypot(dx[:, 0], dx[:, 1])) pl = pl - pl[ind] # Use linear interpolation to get points around label @@ -627,7 +628,7 @@ def labels(self, inline, inline_spacing): # zero in print_label and locate_label. Other than these # functions, this is not necessary and should probably be # eventually removed. - if mlab.is_closed_polygon(lc): + if _is_closed_polygon(lc): slc = np.r_[slc0, slc0[1:2, :]] else: slc = slc0 @@ -688,6 +689,15 @@ def _find_closest_point_on_leg(p1, p2, p0): return d, pc +def _is_closed_polygon(X): + """ + Tests whether first and last object in a sequence are the same. These are + presumably coordinates on a polygonal curve, in which case this function + tests if that curve is closed. + """ + return np.all(X[0] == X[-1]) + + def _find_closest_point_on_path(lc, point): """ lc: coordinates of vertices @@ -702,7 +712,7 @@ def _find_closest_point_on_path(lc, point): xcmin = None legmin = (None, None) - closed = mlab.is_closed_polygon(lc) + closed = _is_closed_polygon(lc) # build list of legs before and after this vertex legs = [] diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index fe1811a12764..45731ee6b222 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -186,6 +186,7 @@ long = int +@cbook.deprecated("2.2", alternative='np.logspace, np.geomspace') def logspace(xmin, xmax, N): ''' Return N values logarithmically spaced between xmin and xmax. @@ -194,14 +195,6 @@ def logspace(xmin, xmax, N): return np.exp(np.linspace(np.log(xmin), np.log(xmax), N)) -def _norm(x): - ''' - Return sqrt(x dot x). - - ''' - return np.sqrt(np.dot(x, x)) - - def window_hanning(x): ''' Return x times the hanning window of len(x). @@ -1348,10 +1341,12 @@ def cohere(x, y, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning, return Cxy, f +@cbook.deprecated('2.2') def donothing_callback(*args): pass +@cbook.deprecated('2.2') def cohere_pairs(X, ij, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning, noverlap=0, preferSpeedOverMemory=True, @@ -1509,6 +1504,7 @@ def cohere_pairs(X, ij, NFFT=256, Fs=2, detrend=detrend_none, return Cxy, Phase, freqs +@cbook.deprecated('2.2') def entropy(y, bins): r""" Return the entropy of the data in *y* in units of nat. @@ -1538,18 +1534,21 @@ def entropy(y, bins): return S +@cbook.deprecated('2.2') def normpdf(x, *args): "Return the normal pdf evaluated at *x*; args provides *mu*, *sigma*" mu, sigma = args return 1./(np.sqrt(2*np.pi)*sigma)*np.exp(-0.5 * (1./sigma*(x - mu))**2) +@cbook.deprecated('2.2') def find(condition): "Return the indices where ravel(condition) is true" res, = np.nonzero(np.ravel(condition)) return res +@cbook.deprecated('2.2') def longest_contiguous_ones(x): """ Return the indices of the longest stretch of contiguous ones in *x*, @@ -1577,11 +1576,13 @@ def longest_contiguous_ones(x): return ind +@cbook.deprecated('2.2') def longest_ones(x): '''alias for longest_contiguous_ones''' return longest_contiguous_ones(x) +@cbook.deprecated('2.2') class PCA(object): def __init__(self, a, standardize=True): """ @@ -1717,6 +1718,7 @@ def _get_colinear(): return a +@cbook.deprecated('2.2') def prctile(x, p=(0.0, 25.0, 50.0, 75.0, 100.0)): """ Return the percentiles of *x*. *p* can either be a sequence of @@ -1756,6 +1758,7 @@ def _interpolate(a, b, fraction): return _interpolate(values[ai], values[bi], frac) +@cbook.deprecated('2.2') def prctile_rank(x, p): """ Return the rank for each element in *x*, return the rank @@ -1781,6 +1784,7 @@ def prctile_rank(x, p): return np.searchsorted(ptiles, x) +@cbook.deprecated('2.2') def center_matrix(M, dim=0): """ Return the matrix *M* with each row having zero mean and unit std. @@ -1797,6 +1801,7 @@ def center_matrix(M, dim=0): return M +@cbook.deprecated('2.2') def rk4(derivs, y0, t): """ Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta. @@ -1868,6 +1873,7 @@ def derivs(x,t): return yout +@cbook.deprecated('2.2') def bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0, mux=0.0, muy=0.0, sigmaxy=0.0): """ @@ -1886,6 +1892,7 @@ def bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0, return np.exp(-z/(2*(1-rho**2))) / denom +@cbook.deprecated('2.2') def get_xyz_where(Z, Cond): """ *Z* and *Cond* are *M* x *N* matrices. *Z* are data and *Cond* is @@ -1898,6 +1905,7 @@ def get_xyz_where(Z, Cond): return X[Cond], Y[Cond], Z[Cond] +@cbook.deprecated('2.2') def get_sparse_matrix(M, N, frac=0.1): """ Return a *M* x *N* sparse matrix with *frac* elements randomly @@ -1911,6 +1919,7 @@ def get_sparse_matrix(M, N, frac=0.1): return data +@cbook.deprecated('2.2') def dist(x, y): """ Return the distance between two points. @@ -1919,6 +1928,7 @@ def dist(x, y): return np.sqrt(np.dot(d, d)) +@cbook.deprecated('2.2') def dist_point_to_segment(p, s0, s1): """ Get the distance of a point to a segment. @@ -1947,6 +1957,7 @@ def dist_point_to_segment(p, s0, s1): return dist(p, pb) +@cbook.deprecated('2.2') def segments_intersect(s1, s2): """ Return *True* if *s1* and *s2* intersect. @@ -1973,6 +1984,7 @@ def segments_intersect(s1, s2): return 0.0 <= u1 <= 1.0 and 0.0 <= u2 <= 1.0 +@cbook.deprecated('2.2') def fftsurr(x, detrend=detrend_none, window=window_none): """ Compute an FFT phase randomized surrogate of *x*. @@ -1988,6 +2000,7 @@ def fftsurr(x, detrend=detrend_none, window=window_none): return np.fft.ifft(z).real +@cbook.deprecated('2.2') def movavg(x, n): """ Compute the len(*n*) moving average of *x*. @@ -2048,6 +2061,7 @@ def movavg(x, n): exp_safe_MAX = 1.7976931348623157e+308 +@cbook.deprecated("2.2") def exp_safe(x): """ Compute exponentials which safely underflow to zero. @@ -2063,6 +2077,7 @@ def exp_safe(x): return math.exp(x) +@cbook.deprecated("2.2", alternative='np.array(list(map(...)))') def amap(fn, *args): """ amap(function, sequence[, sequence, ...]) -> array. @@ -2073,6 +2088,7 @@ def amap(fn, *args): return np.array(list(map(fn, *args))) +@cbook.deprecated("2.2") def rms_flat(a): """ Return the root mean square of all the elements of *a*, flattened out. @@ -2080,6 +2096,7 @@ def rms_flat(a): return np.sqrt(np.mean(np.abs(a) ** 2)) +@cbook.deprecated("2.2", alternative='np.linalg.norm(a, ord=1)') def l1norm(a): """ Return the *l1* norm of *a*, flattened out. @@ -2089,6 +2106,7 @@ def l1norm(a): return np.sum(np.abs(a)) +@cbook.deprecated("2.2", alternative='np.linalg.norm(a, ord=2)') def l2norm(a): """ Return the *l2* norm of *a*, flattened out. @@ -2098,6 +2116,7 @@ def l2norm(a): return np.sqrt(np.sum(np.abs(a) ** 2)) +@cbook.deprecated("2.2", alternative='np.linalg.norm(a.flat, ord=p)') def norm_flat(a, p=2): """ norm(a,p=2) -> l-p norm of a.flat @@ -2115,6 +2134,7 @@ def norm_flat(a, p=2): return np.sum(np.abs(a) ** p) ** (1 / p) +@cbook.deprecated("2.2") def frange(xini, xfin=None, delta=None, **kw): """ frange([start,] stop[, step, keywords]) -> array of floats @@ -2182,6 +2202,7 @@ def frange(xini, xfin=None, delta=None, **kw): # end frange() +@cbook.deprecated("2.2") def identity(n, rank=2, dtype='l', typecode=None): """ Returns the identity matrix of shape (*n*, *n*, ..., *n*) (rank *r*). @@ -2208,6 +2229,7 @@ def identity(n, rank=2, dtype='l', typecode=None): return iden +@cbook.deprecated("2.2") def base_repr(number, base=2, padding=0): """ Return the representation of a *number* in any given *base*. @@ -2223,6 +2245,7 @@ def base_repr(number, base=2, padding=0): max(padding - 1, max_exponent))) +@cbook.deprecated("2.2") def binary_repr(number, max_length=1025): """ Return the binary representation of the input *number* as a @@ -2245,6 +2268,7 @@ def binary_repr(number, max_length=1025): return ''.join(map(repr, digits)).replace('L', '') +@cbook.deprecated("2.2") def log2(x, ln2=math.log(2.0)): """ Return the log(*x*) in base 2. @@ -2263,6 +2287,7 @@ def log2(x, ln2=math.log(2.0)): return len(bin_n) +@cbook.deprecated("2.2") def ispower2(n): """ Returns the log base 2 of *n* if *n* is a power of 2, zero otherwise. @@ -2277,6 +2302,7 @@ def ispower2(n): return len(bin_n) +@cbook.deprecated("2.2") def isvector(X): """ Like the MATLAB function with the same name, returns *True* @@ -2293,7 +2319,7 @@ def isvector(X): # helpers for loading, saving, manipulating and viewing numpy record arrays - +@cbook.deprecated("2.2") def safe_isnan(x): ':func:`numpy.isnan` for arbitrary types' if isinstance(x, six.string_types): @@ -2308,6 +2334,7 @@ def safe_isnan(x): return b +@cbook.deprecated("2.2") def safe_isinf(x): ':func:`numpy.isinf` for arbitrary types' if isinstance(x, six.string_types): @@ -2322,6 +2349,7 @@ def safe_isinf(x): return b +@cbook.deprecated("2.2") def rec_append_fields(rec, names, arrs, dtypes=None): """ Return a new record array with field names populated with data @@ -2358,6 +2386,7 @@ def rec_append_fields(rec, names, arrs, dtypes=None): return newrec +@cbook.deprecated("2.2") def rec_drop_fields(rec, names): """ Return a new numpy record array with fields in *names* dropped. @@ -2375,6 +2404,7 @@ def rec_drop_fields(rec, names): return newrec +@cbook.deprecated("2.2") def rec_keep_fields(rec, names): """ Return a new numpy record array with only fields listed in names @@ -2390,6 +2420,7 @@ def rec_keep_fields(rec, names): return np.rec.fromarrays(arrays, names=names) +@cbook.deprecated("2.2") def rec_groupby(r, groupby, stats): """ *r* is a numpy record array @@ -2433,6 +2464,7 @@ def rec_groupby(r, groupby, stats): return np.rec.fromrecords(rows, names=names) +@cbook.deprecated("2.2") def rec_summarize(r, summaryfuncs): """ *r* is a numpy record array @@ -2455,6 +2487,7 @@ def rec_summarize(r, summaryfuncs): return np.rec.fromarrays(arrays, names=names) +@cbook.deprecated("2.2") def rec_join(key, r1, r2, jointype='inner', defaults=None, r1postfix='1', r2postfix='2'): """ @@ -2598,6 +2631,7 @@ def mapped_r2field(name): return newrec +@cbook.deprecated("2.2") def recs_join(key, name, recs, jointype='outer', missing=0., postfixes=None): """ Join a sequence of record arrays on single column key. @@ -2656,6 +2690,7 @@ def extract(r): return np.rec.fromrecords(results, names=names) +@cbook.deprecated("2.2") def csv2rec(fname, comments='#', skiprows=0, checkrows=0, delimiter=',', converterd=None, names=None, missing='', missingd=None, use_mrecords=False, dayfirst=False, yearfirst=False): @@ -2867,7 +2902,7 @@ def get_converters(reader, comments): break # remove these chars - delete = set(r"""~!@#$%^&*()-=+~\|]}[{';: /?.>,<""") + delete = set(r"""~!@#$%^&*()-=+~\|}[]{';: /?.>,<""") delete.add('"') names = [] @@ -2937,6 +2972,7 @@ def get_converters(reader, comments): # a series of classes for describing the format intentions of various rec views +@cbook.deprecated("2.2") class FormatObj(object): def tostr(self, x): return self.toval(x) @@ -2955,12 +2991,14 @@ def __hash__(self): return hash(self.__class__) +@cbook.deprecated("2.2") class FormatString(FormatObj): def tostr(self, x): val = repr(x) return val[1:-1] +@cbook.deprecated("2.2") class FormatFormatStr(FormatObj): def __init__(self, fmt): self.fmt = fmt @@ -2971,6 +3009,7 @@ def tostr(self, x): return self.fmt % self.toval(x) +@cbook.deprecated("2.2") class FormatFloat(FormatFormatStr): def __init__(self, precision=4, scale=1.): FormatFormatStr.__init__(self, '%%1.%df' % precision) @@ -2989,6 +3028,7 @@ def fromstr(self, s): return float(s)/self.scale +@cbook.deprecated("2.2") class FormatInt(FormatObj): def tostr(self, x): @@ -3001,6 +3041,7 @@ def fromstr(self, s): return int(s) +@cbook.deprecated("2.2") class FormatBool(FormatObj): def toval(self, x): return str(x) @@ -3009,21 +3050,25 @@ def fromstr(self, s): return bool(s) +@cbook.deprecated("2.2") class FormatPercent(FormatFloat): def __init__(self, precision=4): FormatFloat.__init__(self, precision, scale=100.) +@cbook.deprecated("2.2") class FormatThousands(FormatFloat): def __init__(self, precision=4): FormatFloat.__init__(self, precision, scale=1e-3) +@cbook.deprecated("2.2") class FormatMillions(FormatFloat): def __init__(self, precision=4): FormatFloat.__init__(self, precision, scale=1e-6) +@cbook.deprecated("2.2", alternative='date.strftime') class FormatDate(FormatObj): def __init__(self, fmt): self.fmt = fmt @@ -3041,6 +3086,7 @@ def fromstr(self, x): return dateutil.parser.parse(x).date() +@cbook.deprecated("2.2", alternative='datetime.strftime') class FormatDatetime(FormatDate): def __init__(self, fmt='%Y-%m-%d %H:%M:%S'): FormatDate.__init__(self, fmt) @@ -3050,20 +3096,19 @@ def fromstr(self, x): return dateutil.parser.parse(x) -defaultformatd = { - np.bool_: FormatBool(), - np.int16: FormatInt(), - np.int32: FormatInt(), - np.int64: FormatInt(), - np.float32: FormatFloat(), - np.float64: FormatFloat(), - np.object_: FormatObj(), - np.string_: FormatString(), - } - - +@cbook.deprecated("2.2") def get_formatd(r, formatd=None): 'build a formatd guaranteed to have a key for every dtype name' + defaultformatd = { + np.bool_: FormatBool(), + np.int16: FormatInt(), + np.int32: FormatInt(), + np.int64: FormatInt(), + np.float32: FormatFloat(), + np.float64: FormatFloat(), + np.object_: FormatObj(), + np.string_: FormatString()} + if formatd is None: formatd = dict() @@ -3076,6 +3121,7 @@ def get_formatd(r, formatd=None): return formatd +@cbook.deprecated("2.2") def csvformat_factory(format): format = copy.deepcopy(format) if isinstance(format, FormatFloat): @@ -3084,6 +3130,7 @@ def csvformat_factory(format): return format +@cbook.deprecated("2.2", alternative='np.recarray.tofile') def rec2txt(r, header=None, padding=3, precision=3, fields=None): """ Returns a textual representation of a record array. @@ -3204,6 +3251,7 @@ def format(item, just_pad_prec_spacer): return text +@cbook.deprecated("2.2", alternative='np.recarray.tofile') def rec2csv(r, fname, delimiter=',', formatd=None, missing='', missingd=None, withheader=True): """ @@ -3275,9 +3323,10 @@ def newfunc(val, mask, mval): fh.close() +@cbook.deprecated('2.2') def griddata(x, y, z, xi, yi, interp='nn'): - """Interpolates from a nonuniformly spaced grid to some other - grid. + """ + Interpolates from a nonuniformly spaced grid to some other grid. Fits a surface of the form z = f(`x`, `y`) to the data in the (usually) nonuniformly spaced vectors (`x`, `y`, `z`), then @@ -3444,6 +3493,7 @@ def less_simple_linear_interpolation(x, y, xi, extrap=False): return yi +@cbook.deprecated("2.2") def slopes(x, y): """ :func:`slopes` calculates the slope *y*'(*x*) @@ -3485,6 +3535,7 @@ def slopes(x, y): return yp +@cbook.deprecated("2.2") def stineman_interp(xi, x, y, yp=None): """ Given data vectors *x* and *y*, the slope vector *yp* and a new @@ -3738,6 +3789,7 @@ def evaluate(self, points): ################################################## # Code related to things in and around polygons ################################################## +@cbook.deprecated("2.2") def inside_poly(points, verts): """ *points* is a sequence of *x*, *y* points. @@ -3753,6 +3805,7 @@ def inside_poly(points, verts): return [idx for idx, p in enumerate(points) if poly.contains_point(p)] +@cbook.deprecated("2.2") def poly_below(xmin, xs, ys): """ Given a sequence of *xs* and *ys*, return the vertices of a @@ -3783,6 +3836,7 @@ def poly_below(xmin, xs, ys): return x, y +@cbook.deprecated("2.2") def poly_between(x, ylower, yupper): """ Given a sequence of *x*, *ylower* and *yupper*, return the polygon @@ -3810,6 +3864,7 @@ def poly_between(x, ylower, yupper): return x, y +@cbook.deprecated('2.2') def is_closed_polygon(X): """ Tests whether first and last object in a sequence are the same. These are @@ -3819,32 +3874,16 @@ def is_closed_polygon(X): return np.all(X[0] == X[-1]) +@cbook.deprecated("2.2", message='Moved to matplotlib.cbook') def contiguous_regions(mask): """ return a list of (ind0, ind1) such that mask[ind0:ind1].all() is True and we cover all such regions """ - mask = np.asarray(mask, dtype=bool) - - if not mask.size: - return [] - - # Find the indices of region changes, and correct offset - idx, = np.nonzero(mask[:-1] != mask[1:]) - idx += 1 - - # List operations are faster for moderately sized arrays - idx = idx.tolist() - - # Add first and/or last index if needed - if mask[0]: - idx = [0] + idx - if mask[-1]: - idx.append(len(mask)) - - return list(zip(idx[::2], idx[1::2])) + return cbook.contiguous_regions(mask) +@cbook.deprecated("2.2") def cross_from_below(x, threshold): """ return the indices into *x* where *x* crosses some threshold from @@ -3886,6 +3925,7 @@ def cross_from_below(x, threshold): return ind +@cbook.deprecated("2.2") def cross_from_above(x, threshold): """ return the indices into *x* where *x* crosses some threshold from @@ -3909,6 +3949,7 @@ def cross_from_above(x, threshold): ################################################## # Vector and path length geometry calculations ################################################## +@cbook.deprecated('2.2') def vector_lengths(X, P=2., axis=None): """ Finds the length of a set of vectors in *n* dimensions. This is @@ -3923,6 +3964,7 @@ def vector_lengths(X, P=2., axis=None): return (np.sum(X**(P), axis=axis))**(1./P) +@cbook.deprecated('2.2') def distances_along_curve(X): """ Computes the distance between a set of successive points in *N* dimensions. @@ -3935,6 +3977,7 @@ def distances_along_curve(X): return vector_lengths(X, axis=1) +@cbook.deprecated('2.2') def path_length(X): """ Computes the distance travelled along a polygonal curve in *N* dimensions. @@ -3947,6 +3990,7 @@ def path_length(X): return np.concatenate((np.zeros(1), np.cumsum(X))) +@cbook.deprecated('2.2') def quad2cubic(q0x, q0y, q1x, q1y, q2x, q2y): """ Converts a quadratic Bezier curve to a cubic approximation. @@ -3964,6 +4008,7 @@ def quad2cubic(q0x, q0y, q1x, q1y, q2x, q2y): return q0x, q0y, c1x, c1y, c2x, c2y, q2x, q2y +@cbook.deprecated("2.2") def offset_line(y, yerr): """ Offsets an array *y* by +/- an error and returns a tuple diff --git a/lib/matplotlib/tests/test_contour.py b/lib/matplotlib/tests/test_contour.py index c7b4732408f4..35d33b972532 100644 --- a/lib/matplotlib/tests/test_contour.py +++ b/lib/matplotlib/tests/test_contour.py @@ -3,7 +3,6 @@ import datetime import numpy as np -from matplotlib import mlab from matplotlib.testing.decorators import image_comparison from matplotlib import pyplot as plt from numpy.testing import assert_array_almost_equal @@ -260,8 +259,10 @@ def test_labels(): x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) - Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) - Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) + Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi) + Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) / + (2 * np.pi * 0.5 * 1.5)) + # difference of Gaussians Z = 10.0 * (Z2 - Z1) diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index ff9b7d238792..569b7a3808b8 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -13,7 +13,7 @@ from numpy.testing import assert_array_equal from matplotlib import ( - colors, image as mimage, mlab, patches, pyplot as plt, + colors, image as mimage, patches, pyplot as plt, rc_context, rcParams) from matplotlib.image import (AxesImage, BboxImage, FigureImage, NonUniformImage, PcolorImage) @@ -644,8 +644,9 @@ def test_rotate_image(): delta = 0.25 x = y = np.arange(-3.0, 3.0, delta) X, Y = np.meshgrid(x, y) - Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) - Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) + Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi) + Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) / + (2 * np.pi * 0.5 * 1.5)) Z = Z2 - Z1 # difference of Gaussians fig, ax1 = plt.subplots(1, 1) @@ -706,8 +707,9 @@ def test_mask_image_over_under(): delta = 0.025 x = y = np.arange(-3.0, 3.0, delta) X, Y = np.meshgrid(x, y) - Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) - Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) + Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi) + Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) / + (2 * np.pi * 0.5 * 1.5)) Z = 10*(Z2 - Z1) # difference of Gaussians palette = copy(plt.cm.gray) diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index a2909ac7db1b..cd432f713b6c 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -14,6 +14,7 @@ import matplotlib.mlab as mlab import matplotlib.cbook as cbook +from matplotlib.cbook.deprecation import MatplotlibDeprecationWarning try: @@ -23,9 +24,18 @@ HAS_NATGRID = False +''' +A lot of mlab.py has been deprecated in Matplotlib 2.2 and is scheduled for +removal in the future. The tests that use deprecated methods have a block +to catch the deprecation warning, and can be removed with the mlab code is +removed. +''' + + def test_colinear_pca(): - a = mlab.PCA._get_colinear() - pca = mlab.PCA(a) + with pytest.warns(MatplotlibDeprecationWarning): + a = mlab.PCA._get_colinear() + pca = mlab.PCA(a) assert_allclose(pca.fracs[2:], 0., atol=1e-8) assert_allclose(pca.Y[:, 2:], 0., atol=1e-8) @@ -52,17 +62,9 @@ def test_colinear_pca(): [0, 75, 100], ]) def test_prctile(input, percentile): - assert_allclose(mlab.prctile(input, percentile), - np.percentile(input, percentile)) - - -def test_norm(): - np.random.seed(0) - N = 1000 - x = np.random.standard_normal(N) - targ = np.linalg.norm(x) - res = mlab._norm(x) - assert_almost_equal(targ, res) + with pytest.warns(MatplotlibDeprecationWarning): + assert_allclose(mlab.prctile(input, percentile), + np.percentile(input, percentile)) @pytest.mark.parametrize('xmin, xmax, N', [ @@ -77,7 +79,8 @@ def test_norm(): 'single', ]) def test_logspace(xmin, xmax, N): - res = mlab.logspace(xmin, xmax, N) + with pytest.warns(MatplotlibDeprecationWarning): + res = mlab.logspace(xmin, xmax, N) targ = np.logspace(np.log10(xmin), np.log10(xmax), N) assert_allclose(targ, res) assert res.size == N @@ -227,10 +230,10 @@ def test_recarray_csv_roundtrip(tempcsv): expected['x'][:] = np.linspace(-1e9, -1, 99) expected['y'][:] = np.linspace(1, 1e9, 99) expected['t'][:] = np.linspace(0, 0.01, 99) - - mlab.rec2csv(expected, tempcsv) - tempcsv.seek(0) - actual = mlab.csv2rec(tempcsv) + with pytest.warns(MatplotlibDeprecationWarning): + mlab.rec2csv(expected, tempcsv) + tempcsv.seek(0) + actual = mlab.csv2rec(tempcsv) assert_allclose(expected['x'], actual['x']) assert_allclose(expected['y'], actual['y']) @@ -242,14 +245,17 @@ def test_rec2csv_bad_shape_ValueError(tempcsv): (str('y'), float)]) # the bad recarray should trigger a ValueError for having ndim > 1. - with pytest.raises(ValueError): - mlab.rec2csv(bad, tempcsv) + with pytest.warns(MatplotlibDeprecationWarning): + with pytest.raises(ValueError): + mlab.rec2csv(bad, tempcsv) def test_csv2rec_names_with_comments(tempcsv): + tempcsv.write('# comment\n1,2,3\n4,5,6\n') tempcsv.seek(0) - array = mlab.csv2rec(tempcsv, names='a,b,c') + with pytest.warns(MatplotlibDeprecationWarning): + array = mlab.csv2rec(tempcsv, names='a,b,c') assert len(array) == 2 assert len(array.dtype) == 3 @@ -282,7 +288,8 @@ def test_csv2rec_dates(tempcsv, input, kwargs): datetime.datetime(2054, 6, 20, 14, 31, 45), datetime.datetime(2000, 10, 31, 11, 50, 23)] tempcsv.seek(0) - array = mlab.csv2rec(tempcsv, names='a', **kwargs) + with pytest.warns(MatplotlibDeprecationWarning): + array = mlab.csv2rec(tempcsv, names='a', **kwargs) assert_array_equal(array['a'].tolist(), expected) @@ -298,7 +305,8 @@ def test_rec2txt_basic(): truth = (' x y s s2\n' ' 1.000 2 foo bing \n' ' 2.000 3 bar blah ').splitlines() - assert mlab.rec2txt(a).splitlines() == truth + with pytest.warns(MatplotlibDeprecationWarning): + assert mlab.rec2txt(a).splitlines() == truth class TestWindow(object): @@ -2160,18 +2168,21 @@ def get_z(x, y): z = get_z(x, y) xi = [0.2, 0.4, 0.6, 0.8] yi = [0.1, 0.3, 0.7, 0.9] - zi = mlab.griddata(x, y, z, xi, yi, interp='linear') + with pytest.warns(MatplotlibDeprecationWarning): + zi = mlab.griddata(x, y, z, xi, yi, interp='linear') xi, yi = np.meshgrid(xi, yi) np.testing.assert_array_almost_equal(zi, get_z(xi, yi)) # Passing 2D xi and yi arrays to griddata. - zi = mlab.griddata(x, y, z, xi, yi, interp='linear') + with pytest.warns(MatplotlibDeprecationWarning): + zi = mlab.griddata(x, y, z, xi, yi, interp='linear') np.testing.assert_array_almost_equal(zi, get_z(xi, yi)) # Masking z array. z_masked = np.ma.array(z, mask=[False, False, False, True, False]) correct_zi_masked = np.ma.masked_where(xi + yi > 1.0, get_z(xi, yi)) - zi = mlab.griddata(x, y, z_masked, xi, yi, interp='linear') + with pytest.warns(MatplotlibDeprecationWarning): + zi = mlab.griddata(x, y, z_masked, xi, yi, interp='linear') matest.assert_array_almost_equal(zi, correct_zi_masked) np.testing.assert_array_equal(np.ma.getmask(zi), np.ma.getmask(correct_zi_masked)) @@ -2193,24 +2204,28 @@ def get_z(x, y): [0.29999208, 0.8999978, 1.5000029, 2.1000059], [-0.1000099, 0.4999943, 1.0999964, 1.6999979], [-0.3000128, 0.2999894, 0.8999913, 1.4999933]] - zi = mlab.griddata(x, y, z, xi, yi, interp='nn') + with pytest.warns(MatplotlibDeprecationWarning): + zi = mlab.griddata(x, y, z, xi, yi, interp='nn') np.testing.assert_array_almost_equal(zi, correct_zi, 5) - # Decreasing xi or yi should raise ValueError. - with pytest.raises(ValueError): - mlab.griddata(x, y, z, xi[::-1], yi, interp='nn') - with pytest.raises(ValueError): - mlab.griddata(x, y, z, xi, yi[::-1], interp='nn') + with pytest.warns(MatplotlibDeprecationWarning): + # Decreasing xi or yi should raise ValueError. + with pytest.raises(ValueError): + mlab.griddata(x, y, z, xi[::-1], yi, interp='nn') + with pytest.raises(ValueError): + mlab.griddata(x, y, z, xi, yi[::-1], interp='nn') # Passing 2D xi and yi arrays to griddata. xi, yi = np.meshgrid(xi, yi) - zi = mlab.griddata(x, y, z, xi, yi, interp='nn') + with pytest.warns(MatplotlibDeprecationWarning): + zi = mlab.griddata(x, y, z, xi, yi, interp='nn') np.testing.assert_array_almost_equal(zi, correct_zi, 5) # Masking z array. z_masked = np.ma.array(z, mask=[False, False, False, True, False]) correct_zi_masked = np.ma.masked_where(xi + yi > 1.0, correct_zi) - zi = mlab.griddata(x, y, z_masked, xi, yi, interp='nn') + with pytest.warns(MatplotlibDeprecationWarning): + zi = mlab.griddata(x, y, z_masked, xi, yi, interp='nn') np.testing.assert_array_almost_equal(zi, correct_zi_masked, 5) np.testing.assert_array_equal(np.ma.getmask(zi), np.ma.getmask(correct_zi_masked)) @@ -2414,22 +2429,26 @@ def test_contiguous_regions(): # Starts and ends with True mask = [True]*a + [False]*b + [True]*c expected = [(0, a), (a+b, a+b+c)] - assert mlab.contiguous_regions(mask) == expected + with pytest.warns(MatplotlibDeprecationWarning): + assert mlab.contiguous_regions(mask) == expected d, e = 6, 7 # Starts with True ends with False mask = mask + [False]*e - assert mlab.contiguous_regions(mask) == expected + with pytest.warns(MatplotlibDeprecationWarning): + assert mlab.contiguous_regions(mask) == expected # Starts with False ends with True mask = [False]*d + mask[:-e] expected = [(d, d+a), (d+a+b, d+a+b+c)] - assert mlab.contiguous_regions(mask) == expected + with pytest.warns(MatplotlibDeprecationWarning): + assert mlab.contiguous_regions(mask) == expected # Starts and ends with False mask = mask + [False]*e - assert mlab.contiguous_regions(mask) == expected - # No True in mask - assert mlab.contiguous_regions([False]*5) == [] - # Empty mask - assert mlab.contiguous_regions([]) == [] + with pytest.warns(MatplotlibDeprecationWarning): + assert mlab.contiguous_regions(mask) == expected + # No True in mask + assert mlab.contiguous_regions([False]*5) == [] + # Empty mask + assert mlab.contiguous_regions([]) == [] def test_psd_onesided_norm(): diff --git a/lib/matplotlib/widgets.py b/lib/matplotlib/widgets.py index 5a177dc34690..ac6198ff8587 100644 --- a/lib/matplotlib/widgets.py +++ b/lib/matplotlib/widgets.py @@ -19,7 +19,6 @@ import numpy as np from matplotlib import rcParams -from .mlab import dist from .patches import Circle, Rectangle, Ellipse from .lines import Line2D from .transforms import blended_transform_factory @@ -1032,7 +1031,8 @@ def _clicked(self, event): def inside(p): pcirc = np.array([p.center[0], p.center[1]]) - return dist(pclicked, pcirc) < p.radius + d = pclicked - pcirc + return np.sqrt(np.dot(d, d)) < p.radius for i, (p, t) in enumerate(zip(self.circles, self.labels)): if t.get_window_extent().contains(event.x, event.y) or inside(p): diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py index a7f97bef6cdc..66de8d84574e 100644 --- a/lib/mpl_toolkits/mplot3d/axes3d.py +++ b/lib/mpl_toolkits/mplot3d/axes3d.py @@ -2952,13 +2952,12 @@ def get_test_data(delta=0.05): ''' Return a tuple X, Y, Z with a test data set. ''' - - from matplotlib.mlab import bivariate_normal x = y = np.arange(-3.0, 3.0, delta) X, Y = np.meshgrid(x, y) - Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) - Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) + Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi) + Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) / + (2 * np.pi * 0.5 * 1.5)) Z = Z2 - Z1 X = X * 10 @@ -2967,7 +2966,6 @@ def get_test_data(delta=0.05): return X, Y, Z - ######################################################## # Register Axes3D as a 'projection' object available # for use just like any other axes diff --git a/tutorials/colors/colormapnorms.py b/tutorials/colors/colormapnorms.py index eb344f0164fe..3e60e383d2a1 100644 --- a/tutorials/colors/colormapnorms.py +++ b/tutorials/colors/colormapnorms.py @@ -46,7 +46,6 @@ import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors -from matplotlib.mlab import bivariate_normal N = 100 X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] @@ -54,17 +53,18 @@ # A low hump with a spike coming out of the top right. Needs to have # z/colour axis on a log scale so we see both hump and spike. linear # scale only shows the spike. -Z1 = bivariate_normal(X, Y, 0.1, 0.2, 1.0, 1.0) + \ - 0.1 * bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) +Z1 = np.exp(-(X)**2 - (Y)**2) +Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) +Z = Z1 + 50 * Z2 fig, ax = plt.subplots(2, 1) -pcm = ax[0].pcolor(X, Y, Z1, - norm=colors.LogNorm(vmin=Z1.min(), vmax=Z1.max()), +pcm = ax[0].pcolor(X, Y, Z, + norm=colors.LogNorm(vmin=Z.min(), vmax=Z.max()), cmap='PuBu_r') fig.colorbar(pcm, ax=ax[0], extend='max') -pcm = ax[1].pcolor(X, Y, Z1, cmap='PuBu_r') +pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r') fig.colorbar(pcm, ax=ax[1], extend='max') fig.show() @@ -89,19 +89,19 @@ N = 100 X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] -Z1 = (bivariate_normal(X, Y, 1., 1., 1.0, 1.0))**2 \ - - 0.4 * (bivariate_normal(X, Y, 1.0, 1.0, -1.0, 0.0))**2 -Z1 = Z1/0.03 +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 fig, ax = plt.subplots(2, 1) -pcm = ax[0].pcolormesh(X, Y, Z1, +pcm = ax[0].pcolormesh(X, Y, Z, norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03, vmin=-1.0, vmax=1.0), cmap='RdBu_r') fig.colorbar(pcm, ax=ax[0], extend='both') -pcm = ax[1].pcolormesh(X, Y, Z1, cmap='RdBu_r', vmin=-np.max(Z1)) +pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z)) fig.colorbar(pcm, ax=ax[1], extend='both') fig.show() @@ -129,7 +129,7 @@ fig, ax = plt.subplots(2, 1) -pcm = ax[0].pcolormesh(X, Y, Z1, norm=colors.PowerNorm(gamma=1./2.), +pcm = ax[0].pcolormesh(X, Y, Z1, norm=colors.PowerNorm(gamma=0.5), cmap='PuBu_r') fig.colorbar(pcm, ax=ax[0], extend='max') @@ -162,16 +162,16 @@ N = 100 X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] -Z1 = (bivariate_normal(X, Y, 1., 1., 1.0, 1.0))**2 \ - - 0.4 * (bivariate_normal(X, Y, 1.0, 1.0, -1.0, 0.0))**2 -Z1 = Z1/0.03 +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 fig, ax = plt.subplots(3, 1, figsize=(8, 8)) ax = ax.flatten() # even bounds gives a contour-like effect bounds = np.linspace(-1, 1, 10) norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256) -pcm = ax[0].pcolormesh(X, Y, Z1, +pcm = ax[0].pcolormesh(X, Y, Z, norm=norm, cmap='RdBu_r') fig.colorbar(pcm, ax=ax[0], extend='both', orientation='vertical') @@ -179,10 +179,10 @@ # uneven bounds changes the colormapping: bounds = np.array([-0.25, -0.125, 0, 0.5, 1]) norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256) -pcm = ax[1].pcolormesh(X, Y, Z1, norm=norm, cmap='RdBu_r') +pcm = ax[1].pcolormesh(X, Y, Z, norm=norm, cmap='RdBu_r') fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical') -pcm = ax[2].pcolormesh(X, Y, Z1, cmap='RdBu_r', vmin=-np.max(Z1)) +pcm = ax[2].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z)) fig.colorbar(pcm, ax=ax[2], extend='both', orientation='vertical') fig.show() @@ -207,9 +207,9 @@ N = 100 X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] -Z1 = (bivariate_normal(X, Y, 1., 1., 1.0, 1.0))**2 \ - - 0.4 * (bivariate_normal(X, Y, 1.0, 1.0, -1.0, 0.0))**2 -Z1 = Z1/0.03 +Z1 = np.exp(-X**2 - Y**2) +Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) +Z = (Z1 - Z2) * 2 class MidpointNormalize(colors.Normalize): @@ -223,13 +223,14 @@ def __call__(self, value, clip=None): x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] return np.ma.masked_array(np.interp(value, x, y)) + fig, ax = plt.subplots(2, 1) -pcm = ax[0].pcolormesh(X, Y, Z1, +pcm = ax[0].pcolormesh(X, Y, Z, norm=MidpointNormalize(midpoint=0.), cmap='RdBu_r') fig.colorbar(pcm, ax=ax[0], extend='both') -pcm = ax[1].pcolormesh(X, Y, Z1, cmap='RdBu_r', vmin=-np.max(Z1)) +pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z)) fig.colorbar(pcm, ax=ax[1], extend='both') fig.show()