Python matplotlib.pyplot.contour() Examples
The following are 30
code examples of matplotlib.pyplot.contour().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
matplotlib.pyplot
, or try the search function
.
Example #1
Source File: test_patheffects.py From neural-network-animation with MIT License | 8 votes |
def test_collection(): x, y = np.meshgrid(np.linspace(0, 10, 150), np.linspace(-5, 5, 100)) data = np.sin(x) + np.cos(y) cs = plt.contour(data) pe = [path_effects.PathPatchEffect(edgecolor='black', facecolor='none', linewidth=12), path_effects.Stroke(linewidth=5)] for collection in cs.collections: collection.set_path_effects(pe) for text in plt.clabel(cs, colors='white'): text.set_path_effects([path_effects.withStroke(foreground='k', linewidth=3)]) text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none', 'edgecolor': 'blue'})
Example #2
Source File: AnomalyDetection.py From MachineLearning_Python with MIT License | 8 votes |
def visualizeFit(X,mu,sigma2): x = np.arange(0, 36, 0.5) # 0-36,步长0.5 y = np.arange(0, 36, 0.5) X1,X2 = np.meshgrid(x,y) # 要画等高线,所以meshgird Z = multivariateGaussian(np.hstack((X1.reshape(-1,1),X2.reshape(-1,1))), mu, sigma2) # 计算对应的高斯分布函数 Z = Z.reshape(X1.shape) # 调整形状 plt.plot(X[:,0],X[:,1],'bx') if np.sum(np.isinf(Z).astype(float)) == 0: # 如果计算的为无穷,就不用画了 #plt.contourf(X1,X2,Z,10.**np.arange(-20, 0, 3),linewidth=.5) CS = plt.contour(X1,X2,Z,10.**np.arange(-20, 0, 3),color='black',linewidth=.5) # 画等高线,Z的值在10.**np.arange(-20, 0, 3) #plt.clabel(CS) plt.show() # 选择最优的epsilon,即:使F1Score最大
Example #3
Source File: test_patheffects.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_collection(): x, y = np.meshgrid(np.linspace(0, 10, 150), np.linspace(-5, 5, 100)) data = np.sin(x) + np.cos(y) cs = plt.contour(data) pe = [path_effects.PathPatchEffect(edgecolor='black', facecolor='none', linewidth=12), path_effects.Stroke(linewidth=5)] for collection in cs.collections: collection.set_path_effects(pe) for text in plt.clabel(cs, colors='white'): text.set_path_effects([path_effects.withStroke(foreground='k', linewidth=3)]) text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none', 'edgecolor': 'blue'})
Example #4
Source File: test_contour.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_contour_badlevel_fmt(): # test funny edge case from # https://github.com/matplotlib/matplotlib/issues/9742 # User supplied fmt for each level as a dictionary, but # MPL changed the level to the minimum data value because # no contours possible. # This would error out pre # https://github.com/matplotlib/matplotlib/pull/9743 x = np.arange(9) z = np.zeros((9, 9)) fig, ax = plt.subplots() fmt = {1.: '%1.2f'} with pytest.warns(UserWarning) as record: cs = ax.contour(x, x, z, levels=[1.]) ax.clabel(cs, fmt=fmt) assert len(record) == 1
Example #5
Source File: test_contour.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_contour_datetime_axis(): fig = plt.figure() fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15) base = datetime.datetime(2013, 1, 1) x = np.array([base + datetime.timedelta(days=d) for d in range(20)]) y = np.arange(20) z1, z2 = np.meshgrid(np.arange(20), np.arange(20)) z = z1 * z2 plt.subplot(221) plt.contour(x, y, z) plt.subplot(222) plt.contourf(x, y, z) x = np.repeat(x[np.newaxis], 20, axis=0) y = np.repeat(y[:, np.newaxis], 20, axis=1) plt.subplot(223) plt.contour(x, y, z) plt.subplot(224) plt.contourf(x, y, z) for ax in fig.get_axes(): for label in ax.get_xticklabels(): label.set_ha('right') label.set_rotation(30)
Example #6
Source File: test_contour.py From neural-network-animation with MIT License | 6 votes |
def test_contour_shape_mismatch_3(): x = np.arange(10) y = np.arange(10) xg, yg = np.meshgrid(x, y) z = np.random.random((9, 10)) fig = plt.figure() ax = fig.add_subplot(111) try: ax.contour(xg, y, z) except TypeError as exc: assert exc.args[0] == 'Number of dimensions of x and y should match.' try: ax.contour(x, yg, z) except TypeError as exc: assert exc.args[0] == 'Number of dimensions of x and y should match.'
Example #7
Source File: test_contour.py From neural-network-animation with MIT License | 6 votes |
def test_contour_shape_mismatch_4(): g = np.random.random((9, 10)) b = np.random.random((9, 9)) z = np.random.random((9, 10)) fig = plt.figure() ax = fig.add_subplot(111) try: ax.contour(b, g, z) except TypeError as exc: print(exc.args[0]) assert re.match( r'Shape of x does not match that of z: ' + r'found \(9L?, 9L?\) instead of \(9L?, 10L?\)\.', exc.args[0]) is not None try: ax.contour(g, b, z) except TypeError as exc: assert re.match( r'Shape of y does not match that of z: ' + r'found \(9L?, 9L?\) instead of \(9L?, 10L?\)\.', exc.args[0]) is not None
Example #8
Source File: electrostatics.py From electrostatics with GNU General Public License v3.0 | 6 votes |
def plot(self, zmin=-1.5, zmax=1.5, step=0.25, linewidth=1, linestyle=':'): """Plots the field magnitude.""" if linewidth is None: linewidth = matplotlib.rcParams['lines.linewidth'] x, y = meshgrid( linspace(XMIN/ZOOM+XOFFSET, XMAX/ZOOM+XOFFSET, 200), linspace(YMIN/ZOOM, YMAX/ZOOM, 200)) z = zeros_like(x) for i in range(x.shape[0]): for j in range(x.shape[1]): # pylint: disable=unsupported-assignment-operation z[i, j] = self.magnitude([x[i, j], y[i, j]]) # levels = arange(nmin, nmax+0.2, 0.2) # cmap = pyplot.cm.get_cmap('plasma') pyplot.contour(x, y, z, numpy.arange(zmin, zmax+step, step), linewidths=linewidth, linestyles=linestyle, colors='k') # pylint: disable=too-few-public-methods
Example #9
Source File: gmm.py From cupy with MIT License | 6 votes |
def draw(X, pred, means, covariances, output): xp = cupy.get_array_module(X) for i in range(2): labels = X[pred == i] if xp is cupy: labels = labels.get() plt.scatter(labels[:, 0], labels[:, 1], c=np.random.rand(1, 3)) if xp is cupy: means = means.get() covariances = covariances.get() plt.scatter(means[:, 0], means[:, 1], s=120, marker='s', facecolors='y', edgecolors='k') x = np.linspace(-5, 5, 1000) y = np.linspace(-5, 5, 1000) X, Y = np.meshgrid(x, y) for i in range(2): dist = stats.multivariate_normal(means[i], covariances[i]) Z = dist.pdf(np.stack([X, Y], axis=-1)) plt.contour(X, Y, Z) plt.savefig(output)
Example #10
Source File: SVM_scikit-learn.py From MachineLearning_Python with MIT License | 6 votes |
def plot_decisionBoundary(X, y, model, class_='linear'): plt = plot_data(X, y) # 线性边界 if class_ == 'linear': w = model.coef_ b = model.intercept_ xp = np.linspace(np.min(X[:, 0]), np.max(X[:, 0]), 100) yp = -(w[0, 0] * xp + b) / w[0, 1] plt.plot(xp, yp, 'b-', linewidth=2.0) plt.show() else: # 非线性边界 x_1 = np.transpose(np.linspace(np.min(X[:, 0]), np.max(X[:, 0]), 100).reshape(1, -1)) x_2 = np.transpose(np.linspace(np.min(X[:, 1]), np.max(X[:, 1]), 100).reshape(1, -1)) X1, X2 = np.meshgrid(x_1, x_2) vals = np.zeros(X1.shape) for i in range(X1.shape[1]): this_X = np.hstack((X1[:, i].reshape(-1, 1), X2[:, i].reshape(-1, 1))) vals[:, i] = model.predict(this_X) plt.contour(X1, X2, vals, [0, 1], color='blue') plt.show()
Example #11
Source File: test_contour.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_contour_shape_mismatch_4(): g = np.random.random((9, 10)) b = np.random.random((9, 9)) z = np.random.random((9, 10)) fig, ax = plt.subplots() with pytest.raises(TypeError) as excinfo: ax.contour(b, g, z) excinfo.match(r'Shape of x does not match that of z: found \(9L?, 9L?\) ' + r'instead of \(9L?, 10L?\)') with pytest.raises(TypeError) as excinfo: ax.contour(g, b, z) excinfo.match(r'Shape of y does not match that of z: found \(9L?, 9L?\) ' + r'instead of \(9L?, 10L?\)')
Example #12
Source File: dynamical_imaging.py From eht-imaging with GNU General Public License v3.0 | 6 votes |
def Cont(imG): #This is meant to create plots similar to the ones from #https://www.bu.edu/blazars/VLBA_GLAST/3c454.html #for the visual comparison import matplotlib.pyplot as plt plt.figure() Z = np.reshape(imG.imvec,(imG.xdim,imG.ydim)) pov = imG.xdim*imG.psize pov_mas = pov/(RADPERUAS*1.e3) Zmax = np.amax(Z) print(Zmax) levels = np.array((-0.00125*Zmax,0.00125*Zmax,0.0025*Zmax, 0.005*Zmax, 0.01*Zmax, 0.02*Zmax, 0.04*Zmax, 0.08*Zmax, 0.16*Zmax, 0.32*Zmax, 0.64*Zmax)) CS = plt.contour(Z, levels, origin='lower', linewidths=2, extent=(-pov_mas/2., pov_mas/2., -pov_mas/2., pov_mas/2.)) plt.show()
Example #13
Source File: test_contour.py From neural-network-animation with MIT License | 6 votes |
def test_contour_datetime_axis(): fig = plt.figure() fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15) base = datetime.datetime(2013, 1, 1) x = np.array([base + datetime.timedelta(days=d) for d in range(20)]) y = np.arange(20) z1, z2 = np.meshgrid(np.arange(20), np.arange(20)) z = z1 * z2 plt.subplot(221) plt.contour(x, y, z) plt.subplot(222) plt.contourf(x, y, z) x = np.repeat(x[np.newaxis], 20, axis=0) y = np.repeat(y[:, np.newaxis], 20, axis=1) plt.subplot(223) plt.contour(x, y, z) plt.subplot(224) plt.contourf(x, y, z) for ax in fig.get_axes(): for label in ax.get_xticklabels(): label.set_ha('right') label.set_rotation(30)
Example #14
Source File: freesurfer.py From visualqc with Apache License 2.0 | 6 votes |
def plot_contours_in_slice(self, slice_seg, target_axis): """Plots contour around the data in slice (after binarization)""" plt.sca(target_axis) contour_handles = list() for index, label in enumerate(self.unique_labels_display): binary_slice_seg = slice_seg == index if not binary_slice_seg.any(): continue ctr_h = plt.contour(binary_slice_seg, levels=[cfg.contour_level, ], colors=(self.color_for_label[index],), linewidths=cfg.contour_line_width, alpha=self.alpha_seg, zorder=cfg.seg_zorder_freesurfer) contour_handles.append(ctr_h) return contour_handles
Example #15
Source File: test_patheffects.py From ImageFusion with MIT License | 6 votes |
def test_collection(): x, y = np.meshgrid(np.linspace(0, 10, 150), np.linspace(-5, 5, 100)) data = np.sin(x) + np.cos(y) cs = plt.contour(data) pe = [path_effects.PathPatchEffect(edgecolor='black', facecolor='none', linewidth=12), path_effects.Stroke(linewidth=5)] for collection in cs.collections: collection.set_path_effects(pe) for text in plt.clabel(cs, colors='white'): text.set_path_effects([path_effects.withStroke(foreground='k', linewidth=3)]) text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none', 'edgecolor': 'blue'})
Example #16
Source File: thinkplot.py From Lie_to_me with MIT License | 6 votes |
def Pcolor(xs, ys, zs, pcolor=True, contour=False, **options): """Makes a pseudocolor plot. xs: ys: zs: pcolor: boolean, whether to make a pseudocolor plot contour: boolean, whether to make a contour plot options: keyword args passed to plt.pcolor and/or plt.contour """ _Underride(options, linewidth=3, cmap=matplotlib.cm.Blues) X, Y = np.meshgrid(xs, ys) Z = zs x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False) axes = plt.gca() axes.xaxis.set_major_formatter(x_formatter) if pcolor: plt.pcolormesh(X, Y, Z, **options) if contour: cs = plt.contour(X, Y, Z, **options) plt.clabel(cs, inline=1, fontsize=10)
Example #17
Source File: accelerator.py From ocelot with GNU General Public License v3.0 | 6 votes |
def show_da(out_da, x_array, y_array, title=""): nx = len(x_array) ny = len(y_array) out_da = out_da.reshape(ny,nx) xmin, xmax, ymin, ymax = np.min(x_array), np.max(x_array), np.min(y_array), np.max(y_array) extent = xmin, xmax, ymin, ymax plt.figure(figsize=(10, 7)) fig1 = plt.contour(out_da, linewidths=2,extent = extent)#, colors = 'r') plt.grid(True) plt.title(title) plt.xlabel("X, m") plt.ylabel("Y, m") cb = plt.colorbar() cb.set_label('Nturns') plt.show()
Example #18
Source File: test_contour.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_contour_shape_mismatch_3(): x = np.arange(10) y = np.arange(10) xg, yg = np.meshgrid(x, y) z = np.random.random((9, 10)) fig, ax = plt.subplots() with pytest.raises(TypeError) as excinfo: ax.contour(xg, y, z) excinfo.match(r'Number of dimensions of x and y should match.') with pytest.raises(TypeError) as excinfo: ax.contour(x, yg, z) excinfo.match(r'Number of dimensions of x and y should match.')
Example #19
Source File: test_contour.py From neural-network-animation with MIT License | 6 votes |
def test_labels(): # Adapted from pylab_examples example code: contour_demo.py # see issues #2475, #2843, and #2818 for explanation delta = 0.025 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) fig, ax = plt.subplots(1, 1) CS = ax.contour(X, Y, Z) disp_units = [(216, 177), (359, 290), (521, 406)] data_units = [(-2, .5), (0, -1.5), (2.8, 1)] CS.clabel() for x, y in data_units: CS.add_label_near(x, y, inline=True, transform=None) for x, y in disp_units: CS.add_label_near(x, y, inline=True, transform=False)
Example #20
Source File: test_contour.py From neural-network-animation with MIT License | 6 votes |
def test_given_colors_levels_and_extends(): _, axes = plt.subplots(2, 4) data = np.arange(12).reshape(3, 4) colors = ['red', 'yellow', 'pink', 'blue', 'black'] levels = [2, 4, 8, 10] for i, ax in enumerate(axes.flatten()): plt.sca(ax) filled = i % 2 == 0. extend = ['neither', 'min', 'max', 'both'][i // 2] if filled: last_color = -1 if extend in ['min', 'max'] else None plt.contourf(data, colors=colors[:last_color], levels=levels, extend=extend) else: last_level = -1 if extend == 'both' else None plt.contour(data, colors=colors, levels=levels[:last_level], extend=extend) plt.colorbar()
Example #21
Source File: test_contour.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_contour_shape_mismatch_2(): x = np.arange(10) y = np.arange(10) z = np.random.random((9, 10)) fig, ax = plt.subplots() with pytest.raises(TypeError) as excinfo: ax.contour(x, y, z) excinfo.match(r'Length of y must be number of rows in z.')
Example #22
Source File: test_contour.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_contour_shape_invalid_1(): x = np.random.random((3, 3, 3)) y = np.random.random((3, 3, 3)) z = np.random.random((9, 10)) fig, ax = plt.subplots() with pytest.raises(TypeError) as excinfo: ax.contour(x, y, z) excinfo.match(r'Inputs x and y must be 1D or 2D.')
Example #23
Source File: test_contour.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_contour_shape_2d_valid(): x = np.arange(10) y = np.arange(9) xg, yg = np.meshgrid(x, y) z = np.random.random((9, 10)) fig, ax = plt.subplots() ax.contour(xg, yg, z)
Example #24
Source File: test_contour.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_contour_shape_invalid_2(): x = np.random.random((3, 3, 3)) y = np.random.random((3, 3, 3)) z = np.random.random((3, 3, 3)) fig, ax = plt.subplots() with pytest.raises(TypeError) as excinfo: ax.contour(x, y, z) excinfo.match(r'Input z must be a 2D array.')
Example #25
Source File: test_contour.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_contour_Nlevels(): # A scalar levels arg or kwarg should trigger auto level generation. # https://github.com/matplotlib/matplotlib/issues/11913 z = np.arange(12).reshape((3, 4)) fig, ax = plt.subplots() cs1 = ax.contour(z, 5) assert len(cs1.levels) > 1 cs2 = ax.contour(z, levels=5) assert (cs1.levels == cs2.levels).all()
Example #26
Source File: test_contour.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_contour_shape_1d_valid(): x = np.arange(10) y = np.arange(9) z = np.random.random((9, 10)) fig, ax = plt.subplots() ax.contour(x, y, z)
Example #27
Source File: test_contour.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_contour_1x1_array(): # github issue 8197 with pytest.raises(TypeError) as excinfo: plt.contour([[0]]) excinfo.match(r'Input z must be at least a 2x2 array.') with pytest.raises(TypeError) as excinfo: plt.contour([0], [0], [[0]]) excinfo.match(r'Input z must be at least a 2x2 array.')
Example #28
Source File: test_contour.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_contour_uniform_z(): x = np.arange(9) z = np.ones((9, 9)) fig, ax = plt.subplots() with pytest.warns(UserWarning) as record: ax.contour(x, x, z) assert len(record) == 1
Example #29
Source File: plot_stability.py From pySDC with BSD 2-Clause "Simplified" License | 5 votes |
def plot_stability(lambda_s, lambda_f, num_nodes, K, stab): """ Plotting routine of the stability domains Args: lambda_s (numpy.ndarray): lambda_slow lambda_f (numpy.ndarray): lambda_fast num_nodes (int): number of collocation nodes K (int): number of iterations stab (numpy.ndarray): stability numbers """ lam_s_max = np.amax(lambda_s.imag) lam_f_max = np.amax(lambda_f.imag) rcParams['figure.figsize'] = 1.5, 1.5 fs = 8 fig = plt.figure() levels = np.array([0.25, 0.5, 0.75, 0.9, 1.1]) CS1 = plt.contour(lambda_s.imag, lambda_f.imag, np.absolute(stab), levels, colors='k', linestyles='dashed') CS2 = plt.contour(lambda_s.imag, lambda_f.imag, np.absolute(stab), [1.0], colors='k') # Set markers at points used in plot_stab_vs_k plt.plot(4, 10, 'x', color='k', markersize=fs - 4) plt.plot(1, 10, 'x', color='k', markersize=fs - 4) plt.clabel(CS1, inline=True, fmt='%3.2f', fontsize=fs - 2) manual_locations = [(1.5, 2.5)] if K > 0: # for K=0 and no 1.0 isoline, this crashes Matplotlib for somer reason plt.clabel(CS2, inline=True, fmt='%3.2f', fontsize=fs - 2, manual=manual_locations) plt.gca().add_patch(Polygon([[0, 0], [lam_s_max, 0], [lam_s_max, lam_s_max]], visible=True, fill=True, facecolor='.75', edgecolor='k', linewidth=1.0, zorder=11)) plt.gca().set_xticks(np.arange(0, int(lam_s_max) + 1)) plt.gca().set_yticks(np.arange(0, int(lam_f_max) + 2, 2)) plt.gca().tick_params(axis='both', which='both', labelsize=fs) plt.xlim([0.0, lam_s_max]) plt.ylim([0.0, lam_f_max]) plt.xlabel('$\Delta t \lambda_{slow}$', fontsize=fs, labelpad=0.0) plt.ylabel('$\Delta t \lambda_{fast}$', fontsize=fs, labelpad=0.0) plt.title(r'$M=%1i$, $K=%1i$' % (num_nodes, K), fontsize=fs) filename = 'data/stability-K' + str(K) + '-M' + str(num_nodes) + '.png' fig.savefig(filename, bbox_inches='tight')
Example #30
Source File: lens_model_extensions.py From lenstronomy with MIT License | 5 votes |
def critical_curve_caustics(self, kwargs_lens, compute_window=5, grid_scale=0.01): """ :param kwargs_lens: lens model kwargs :param compute_window: window size in arcsec where the critical curve is computed :param grid_scale: numerical grid spacing of the computation of the critical curves :return: lists of ra and dec arrays corresponding to different disconnected critical curves and their caustic counterparts """ numPix = int(compute_window / grid_scale) x_grid_high_res, y_grid_high_res = util.make_grid(numPix, deltapix=grid_scale, subgrid_res=1) mag_high_res = util.array2image(self._lensModel.magnification(x_grid_high_res, y_grid_high_res, kwargs_lens)) ra_crit_list = [] dec_crit_list = [] ra_caustic_list = [] dec_caustic_list = [] import matplotlib.pyplot as plt cs = plt.contour(util.array2image(x_grid_high_res), util.array2image(y_grid_high_res), mag_high_res, [0], alpha=0.0) paths = cs.collections[0].get_paths() for i, p in enumerate(paths): v = p.vertices ra_points = v[:, 0] dec_points = v[:, 1] ra_crit_list.append(ra_points) dec_crit_list.append(dec_points) ra_caustics, dec_caustics = self._lensModel.ray_shooting(ra_points, dec_points, kwargs_lens) ra_caustic_list.append(ra_caustics) dec_caustic_list.append(dec_caustics) plt.cla() return ra_crit_list, dec_crit_list, ra_caustic_list, dec_caustic_list