我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.contour()。
def plot_density_map(x, y, xbins, ybins, Nlevels=4, cbar=True, weights=None): Z = np.histogram2d(x, y, bins=(xbins, ybins), weights=weights)[0].astype(float).T # central values lt = get_centers_from_bins(xbins) lm = get_centers_from_bins(ybins) cX, cY = np.meshgrid(lt, lm) X, Y = np.meshgrid(xbins, ybins) im = plt.pcolor(X, Y, Z, cmap=plt.cm.Blues) plt.contour(cX, cY, Z, levels=nice_levels(Z, Nlevels), cmap=plt.cm.Greys_r) if cbar: cb = plt.colorbar(im) else: cb = None plt.xlim(xbins[0], xbins[-1]) plt.ylim(ybins[0], ybins[-1]) try: plt.tight_layout() except Exception as e: print(e) return plt.gca(), cb
def plot2d_simplex(simplex, ind): fig_dir = "./" plt.cla() n = 1000 x1 = np.linspace(-256, 1024, n) x2 = np.linspace(-256, 1024, n) X, Y = np.meshgrid(x1, x2) Z = np.sqrt(X ** 2 + Y ** 2) plt.contour(X, Y, Z, levels=list(np.arange(0, 1200, 10))) plt.gca().set_aspect("equal") plt.xlim((-256, 768)) plt.ylim((-256, 768)) plt.plot([simplex[0].x[0], simplex[1].x[0]], [simplex[0].x[1], simplex[1].x[1]], color="#000000") plt.plot([simplex[1].x[0], simplex[2].x[0]], [simplex[1].x[1], simplex[2].x[1]], color="#000000") plt.plot([simplex[2].x[0], simplex[0].x[0]], [simplex[2].x[1], simplex[0].x[1]], color="#000000") plt.savefig(os.path.join(fig_dir, "{:03d}.png".format(ind)))
def showHeightMap(x,y,z,zi): ''' show height map in maptplotlib ''' zi=zi.transpose() plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower', extent=[ y.min(), y.max(),x.min(), x.max()]) plt.colorbar() CS = plt.contour(zi,15,linewidths=0.5,colors='k', extent=[ y.min(), y.max(),x.min(), x.max()]) CS = plt.contourf(zi,15,cmap=plt.cm.rainbow, extent=[ y.min(), y.max(),x.min(), x.max()]) z=z.transpose() plt.scatter(y, x, c=z) # achsen umkehren #plt.gca().invert_xaxis() #plt.gca().invert_yaxis() plt.show() return
def draw(X, pred, means, covariances, output): xp = cupy.get_array_module(X) for i in six.moves.range(2): labels = X[pred == i] if xp is cupy: labels = labels.get() plt.scatter(labels[:, 0], labels[:, 1], c=np.random.rand(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 six.moves.range(2): Z = mlab.bivariate_normal(X, Y, np.sqrt(covariances[i][0]), np.sqrt(covariances[i][1]), means[i][0], means[i][1]) plt.contour(X, Y, Z) plt.savefig(output)
def maskfill_edgeinclude(a, iterations=1, erode=False): import scipy.ndimage as ndimage a = checkma(a) if erode: a = mask_islands(a, iterations=1) #This is the dilation version #newmask = ~np.ma.getmaskarray(a) #newmask = ndimage.morphology.binary_dilation(newmask, iterations=iterations) #newmask = ndimage.morphology.binary_dilation(~newmask, iterations=iterations) #And the erosion version newmask = np.ma.getmaskarray(a) newmask = ndimage.morphology.binary_erosion(newmask, iterations=iterations) newmask = ndimage.morphology.binary_dilation(newmask, iterations=iterations) return newmask #This is an alternative to the ma.notmasked_edges #Note: probably faster/simpler to contour the mask
def contour_edges(a): import matplotlib.pyplot as plt a = checkma(a) #Contour nodata value levels = [a.fill_value] #kw = {'antialiased':True, 'colors':'r', 'linestyles':'-'} kw = {'antialiased':True} #Generate contours around nodata cs = plt.contour(a.filled(), levels, **kw) #This returns a list of numpy arrays #allpts = np.vstack(cs.allsegs[0]) #Extract paths p = cs.collections[0].get_paths() #Sort by number of vertices in each path p_len = [i.vertices.shape[0] for i in p] p_sort = [x for (y,x) in sorted(zip(p_len,p), reverse=True)] #cp = p[0].make_compound_path(*p) return p_sort #Brute force search for edges of valid data
def detect_contour(img, level): #parameter mask = None; corner_mask = True; nchunk = 0; #prepare image data z = ma.asarray(img, dtype=np.float64); ny, nx = z.shape; x, y = np.meshgrid(np.arange(nx), np.arange(ny)); #find contour contour_generator = _contour.QuadContourGenerator(x, y, z.filled(), mask, corner_mask, nchunk) vertices = contour_generator.create_contour(level); return vertices;
def plot_decision_boundary(pred_func, X, y, bounds, filename=None): if plt is None: return fig = plt.figure() h = 0.01 # Generate a grid of points with distance h between them x_min, x_max, y_min, y_max = bounds xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # Predict the function value for the whole gid Z = pred_func(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # Plot the contour and training examples plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral) plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral) if filename: plt.savefig(filename) plt.close() else: plt.show() return fig
def compare_boundaries(pred_func1, pred_func2, bounds, filename=None): if plt is None: return # Set min and max values and give it some padding x_min, x_max, y_min, y_max = bounds h = 0.01 # Generate a grid of points with distance h between them xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # Predict the function value for the whole gid Z1 = pred_func1(np.c_[xx.ravel(), yy.ravel()]) Z1 = Z1.reshape(xx.shape) plt.figure() # Plot the contour and training examples plt.contour(xx, yy, Z1, cmap=plt.cm.Reds) Z2 = pred_func2(np.c_[xx.ravel(), yy.ravel()]) Z2 = Z2.reshape(xx.shape) # Plot the contour and training examples plt.contour(xx, yy, Z2, cmap=plt.cm.Blues) if filename: plt.savefig(filename) plt.close() else: plt.show()
def plot_decision_boundary(pred_func, X, y, bounds, filename=None): if plt is None: return plt.figure() h = 0.01 # Generate a grid of points with distance h between them x_min, x_max, y_min, y_max = bounds xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # Predict the function value for the whole gid Z = pred_func(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # Plot the contour and training examples plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral) plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral) if filename: plt.savefig(filename) plt.close() else: plt.show()
def compare_decision_boundary(pred_func1, pred_func2, X, filename): if plt is None: return # Set min and max values and give it some padding x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 h = 0.01 # Generate a grid of points with distance h between them xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # Predict the function value for the whole gid Z1 = pred_func1(np.c_[xx.ravel(), yy.ravel()]) Z1 = Z1.reshape(xx.shape) plt.figure() # Plot the contour and training examples plt.contour(xx, yy, Z1, cmap=plt.cm.Reds) Z2 = pred_func2(np.c_[xx.ravel(), yy.ravel()]) Z2 = Z2.reshape(xx.shape) # Plot the contour and training examples plt.contour(xx, yy, Z2, cmap=plt.cm.Blues) plt.savefig(filename) plt.close()
def plot_model(model, data): """ :param model: the GMM model :param data: the data set 2D :return: """ delta = 0.025 x = np.arange(0.0, 4, delta) y = np.arange(0.0, 4, delta) X, Y = np.meshgrid(x, y) z = np.zeros((np.size(x), np.size(y))) # sum of Gaussian plt.figure() for i in range(np.size(model)): ztemp = mlab.bivariate_normal(X, Y, np.sqrt(model['cov'][i][0, 0]), np.sqrt(model['cov'][i][1, 1]), model['mu'][i][0], model['mu'][i][1], model['cov'][i][0,1]) plt.contour(X, Y, model['w'][i]*ztemp) z = np.add(z, ztemp) plt.scatter(data[0, :], data[1, :], s=5) plt.figure() plt.contour(X, Y, z*np.size(model)) plt.scatter(data[0, :], data[1, :], s=5)
def scatter_plot(x, y, ellipse=False, levels=[0.99, 0.95, 0.68], color='w', ax=None, **kwargs): if ax is None: ax = plt.gca() if faststats is not None: im, e = faststats.fastkde.fastkde(x, y, (50, 50), adjust=2.) V = im.max() * np.asarray(levels) plt.contour(im.T, levels=V, origin='lower', extent=e, linewidths=[1, 2, 3], colors=color) ax.plot(x, y, 'b,', alpha=0.3, zorder=-1, rasterized=True) if ellipse is True: data = np.vstack([x, y]) mu = np.mean(data, axis=1) cov = np.cov(data) error_ellipse(mu, cov, ax=plt.gca(), edgecolor="g", ls="dashed", lw=4, zorder=2)
def plot_reg_2D_stoc(X,stoc_vector): deter_vec = np.invert(stoc_vector) dom_max = np.amax(X[stoc_vector,:]) + 1 A = np.zeros((dom_max,dom_max)) stoc_indexs = np.arange(0,X.shape[0],1)[stoc_vector].astype(int) for i,deter_element in enumerate(deter_vec): if deter_element == True: A[X[int(stoc_indexs[0]),:].astype(int), X[int(stoc_indexs[1]),:].astype(int)] = X[i,:] pl.figure(i) #ax = fig.gca(projection='3d') #surf = ax.plot_surface(X[int(stoc_indexs[0]),:].astype(int), X[int(stoc_indexs[1]),:].astype(int),X[i,:], rstride=1, cstride=1, #cmap=cm.coolwarm,linewidth=0, antialiased=False) pl.contour(A,X[i,:]) #ax.zaxis.set_major_locator(LinearLocator(10)) #ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) #fig.colorbar(surf, shrink=0.5, aspect=5) pl.show()
def plot_2D_contour(states,p,labels,inter=False): import pylab as pl from pyme.statistics import expectation as EXP exp = EXP((states,p)) X = np.unique(states[0,:]) Y = np.unique(states[1,:]) X_len = len(X) Y_len = len(Y) Z = np.zeros((X.max()+1,Y.max()+1)) for i in range(len(p)): Z[states[0,i],states[1,i]] = p[i] Z = np.where(Z < 1e-8,0.0,Z) pl.clf() XX, YY = np.meshgrid(X,Y) pl.contour(range(X.max()+1),range(Y.max()+1),Z.T) pl.axhline(y=exp[1]) pl.axvline(x=exp[0]) pl.xlabel(labels[0]) pl.ylabel(labels[1]) if inter == True: pl.draw() else: pl.show()
def plot(self, X): nSize, nFeat = X.shape if nFeat != 2: logger.warning('feature number must be 2.') return logger.info('start plotting...') pred = self._predict(X) h = 0.02 # step size in the mesh x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = self._predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.scatter(X[:, 0], X[:, 1], c=pred, cmap=plt.cm.Paired) plt.contour(xx, yy, Z, cmap=plt.cm.Paired) plt.show()
def plot_price_with_time_contours(smoothed_prices, walking_time): map_image = sp.ndimage.imread('map.png') plt.imshow(map_image.mean(2), interpolation='nearest', cmap=plt.cm.gray) zoomed_prices = sp.ndimage.zoom(smoothed_prices, map_image.shape[1]/float(smoothed_prices.shape[0])) plt.imshow(zoomed_prices.T[::-1], alpha=0.5, interpolation='nearest', cmap=plt.cm.viridis, vmin=5.25, vmax=5.75) plt.colorbar(fraction=0.03) smoothed_times = smooth(walking_time, sigma=2) zoomed_times = sp.ndimage.zoom(smoothed_times, map_image.shape[1]/float(smoothed_prices.shape[0])) plt.contour(zoomed_times.T[::-1], cmap=plt.cm.Reds, levels=range(15, 61, 15), linewidths=3) plt.gcf().set_size_inches(36, 36) plt.savefig(os.path.join(OUTPUT_PATH, 'price_with_time_contours.png'), bbox_inches='tight')
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 pyplot.pcolor and/or pyplot.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 = pyplot.gca() axes.xaxis.set_major_formatter(x_formatter) if pcolor: pyplot.pcolormesh(X, Y, Z, **options) if contour: cs = pyplot.contour(X, Y, Z, **options) pyplot.clabel(cs, inline=1, fontsize=10)
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)
def plot_proba_map(i, lat,lon, clusters, class_prob, label, lat_event, lon_event): plt.clf() class_prob = class_prob / np.sum(class_prob) assert np.isclose(np.sum(class_prob),1) risk_map = np.zeros_like(clusters,dtype=np.float64) for cluster_id in range(len(class_prob)): x,y = np.where(clusters == cluster_id) risk_map[x,y] = class_prob[cluster_id] plt.contourf(lon,lat,risk_map,cmap='YlOrRd',alpha=0.9, origin='lower',vmin=0.0,vmax=1.0) plt.colorbar() plt.plot(lon_event, lat_event, marker='+',c='k',lw='5') plt.contour(lon,lat,clusters,colors='k',hold='on') plt.xlim((min(lon),max(lon))) plt.ylim((min(lat),max(lat))) png_name = os.path.join(args.output, '{}_pred_{}_label_{}.eps'.format(i,np.argmax(class_prob), label)) plt.savefig(png_name) plt.close()
def mcontour(xs, ys, fs, levels=None, **kw): """ wrapper function for contour example ====== mcontour(linspace(-4,4),linspace(-4,4),lambda x,y: x*y) """ x,y=np.meshgrid(xs,ys) z=fs(x,y) if levels!=None: plt.contour(x,y,z,sorted(set(levels)),**kw) else: plt.contour(x,y,z,**kw)
def imvort(self,kt,cax=[-1,1],scaled=None,maxi=None): t,z2d = self.read_crop('vorticity',kt) t,psi = self.read_crop('psi',kt) z2d[z2d==0]=nan cm=redblue(nstripes=10) cm.set_bad((0.3,0.3,0.3,1)) if scaled==None: im=plt.imshow(flipud(z2d),vmin=cax[0],vmax=cax[1],cmap=cm,extent=self.domain) else: idx=where(~isnan(z2d)) print('\n',shape(idx)) #wc = median(abs(z2d[idx[0],idx[1]])) wc = median(abs(z2d[idx])) print('wc=%g'%wc) z2d = flipud(z2d) im=plt.imshow(sign(z2d)*log(1+(z2d/wc)**2),vmin=-12,vmax=12,cmap=cm,extent=self.domain) plt.colorbar(im) if maxi == None: maxi = roundlog( max(abs(psi))) #print(linspace(-maxi,maxi,21)) ci = maxi/10 if scaled==None: plt.annotate('CI=%2g'%ci,(0.95,0.05),xycoords='axes fraction',color='g',fontsize=16,horizontalalignment='right') plt.contour(self.x[self.xidx],self.y[self.yidx],psi,linspace(-maxi,maxi,21),colors='g',linewidths=2) #'ci=%2g'%ci #plt.contour(psi,[0],colors='k',linewidths=2) if scaled==None: plt.title('N = %i / t = %4.2f'%(self.nx,t),fontsize=14) plt.xlabel('x') plt.ylabel('y') else: plt.title(r'$t_v=%4.0f$'%t,fontsize=16) plt.xlabel(r'$x$',fontsize=16) plt.ylabel(r'$y$',fontsize=16)
def main(): # Part of the example at # http://matplotlib.sourceforge.net/plot_directive/mpl_examples/pylab_examples/contour_demo.py delta = 0.025 x = numpy.arange(-3.0, 3.0, delta) y = numpy.arange(-2.0, 2.0, delta) X, Y = numpy.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.0 * (Z2 - Z1) pyplot.figure() CS = pyplot.contour(X, Y, Z) pyplot.show()
def plot_smoothed_coord(self,save=False,path=None): fig = plt.figure() plt.title('s = %i' % self.s,fontsize=18,fontweight='bold') plt.contour(self.y1v,self.y2v,self.smoothed_coord_density) plt.scatter(self.coord[:,0],self.coord[:,1]) #plt.axis('scaled') plt.axis([-22,22,-15,15]) plt.show() if save: if path is None: raise ValueError('must specify path to save figure') else: fig.savefig(path+self.name+'_smoothed_coord_s%i'%self.s+'.pdf',bbox_inches='tight')
def plotBoundary(mytheta, myX, myy, mylambda=0.): """ Function to plot the decision boundary for arbitrary theta, X, y, lambda value Inside of this function is feature mapping, and the minimization routine. It works by making a grid of x1 ("xvals") and x2 ("yvals") points, And for each, computing whether the hypothesis classifies that point as True or False. Then, a contour is drawn with a built-in pyplot function. """ theta, mincost = optimizeRegularizedTheta(mytheta,myX,myy,mylambda) xvals = np.linspace(-1,1.5,50) yvals = np.linspace(-1,1.5,50) zvals = np.zeros((len(xvals),len(yvals))) for i in range(len(xvals)): for j in range(len(yvals)): myfeaturesij = mapFeature(np.array([xvals[i]]),np.array([yvals[j]])) zvals[i][j] = np.dot(theta,myfeaturesij.T) zvals = zvals.transpose() u, v = np.meshgrid( xvals, yvals ) mycontour = plt.contour( xvals, yvals, zvals, [0]) #Kind of a hacky way to display a text on top of the decision boundary myfmt = { 0:'Lambda = %d'%mylambda} plt.clabel(mycontour, inline=1, fontsize=15, fmt=myfmt) plt.title("Decision Boundary") #Build a figure showing contours for various values of regularization parameter, lambda #It shows for lambda=0 we are overfitting, and for lambda=100 we are underfitting
def contour(self,title='',cbartitle = '',model=[], zmax = None, zmin = None, filename = None, resolution = 1, unit_str = '', bar = True): """ Returns a figure with contourplot of 2D spatial data. Insert filename to save the figure as an image. Increase resolution to increase detail of interpolated data (<1 to decrease)""" font = {'weight' : 'medium', 'size' : 22} xi = np.linspace(min(self.data.x), max(self.data.x),len(set(self.data.x))*resolution) yi = np.linspace(min(self.data.y), max(self.data.y),len(set(self.data.y))*resolution) zi = ml.griddata(self.data.x, self.data.y, self.data.v.interpolate(), xi, yi,interp='linear') fig = plt.figure() plt.rc('font', **font) plt.title(title) plt.contour(xi, yi, zi, 15, linewidths = 0, cmap=plt.cm.bone) plt.pcolormesh(xi, yi, zi, cmap = plt.get_cmap('rainbow'),vmax = zmax, vmin = zmin) if bar: cbar = plt.colorbar(); cbar.ax.set_ylabel(cbartitle) plt.absolute_import try: vertices = [(vertex.X(), vertex.Y()) for vertex in pyliburo.py3dmodel.fetch.vertex_list_2_point_list(pyliburo.py3dmodel.fetch.topos_frm_compound(model)["vertex"])] shape = patches.PathPatch(Path(vertices), facecolor='white', lw=0) plt.gca().add_patch(shape) except TypeError: pass plt.show() try: fig.savefig(filename) except TypeError: return fig # def plot_along_line(self,X,Y, tick_list): # V = self.data.v # plt.plot(heights, SVFs_can, label='Canyon')
def normals_from_contour_discrete(contour): """Returns normal vectors along the contour Arguments: contours (Curve or 2xn array): contour Returns: nx2 array: normals corresponding to the contours Note: Assumes closed contour with contour[0]==contour[-1] for all i. """ if isinstance(contour, Curve): contour = contour.values; if not np.allclose(contour[0], contour[-1]): raise ValueError('contour not closed!'); #vectors along contour line centervec = np.diff(contour, axis = 0); # absolute orientation t0 = np.array([1,0], dtype = float); #vertical reference t1 = centervec[0]; orientation = np.mod(np.arctan2(t0[0], t0[1]) - np.arctan2(t1[0], t1[1]) + np.pi, 2 * np.pi) - np.pi; # discrete thetas (no rescaling) theta = np.arctan2(centervec[:-1,0], centervec[:-1,1]) - np.arctan2(centervec[1:,0], centervec[1:,1]); theta = np.mod(theta + np.pi, 2 * np.pi) - np.pi; theta = np.hstack([0, theta]); # integrate and rotate by pi/2 / half angle at point itheta = np.cumsum(theta); itheta += np.pi/2 + orientation; itheta -= theta / 2; itheta[0] -= theta[-1] / 2; #ithetas.append(itheta); return np.vstack([np.cos(itheta), np.sin(itheta)]).T;
def generate_image(true_dist): """ Generates and saves a plot of the true distribution, the generator, and the critic. """ N_POINTS = 128 RANGE = 3 points = np.zeros((N_POINTS, N_POINTS, 2), dtype='float32') points[:,:,0] = np.linspace(-RANGE, RANGE, N_POINTS)[:,None] points[:,:,1] = np.linspace(-RANGE, RANGE, N_POINTS)[None,:] points = points.reshape((-1,2)) samples, disc_map = session.run( [fake_data, disc_real], feed_dict={real_data:points} ) disc_map = session.run(disc_real, feed_dict={real_data:points}) plt.clf() x = y = np.linspace(-RANGE, RANGE, N_POINTS) plt.contour(x,y,disc_map.reshape((len(x), len(y))).transpose()) plt.scatter(true_dist[:, 0], true_dist[:, 1], c='orange', marker='+') plt.scatter(samples[:, 0], samples[:, 1], c='green', marker='+') plt.savefig('frame'+str(frame_index[0])+'.jpg') frame_index[0] += 1 # Dataset iterator
def draw_decision_boundary(self, data, X, theta): self.draw(data) x1_min, x1_max = X[:, 1].min(), X[:, 1].max() x2_min, x2_max = X[:, 2].min(), X[:, 2].max() x1_range, x2_range = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max)) h = self.sigmoid(np.c_[np.ones((x1_range.ravel().shape[0], 1)), x1_range.ravel(), x2_range.ravel()].dot(theta)) h = h.reshape(x1_range.shape) plt.contour(x1_range, x2_range, h, [0.5], linewiths=1, colors='b') plt.show()
def ContourSet(img): med_img = medfilt(img,kernel_size=11) cs = plt.contour(med_img, np.arange(0.1,2,0.1), origin='lower') return cs
def plot_lr(self): xx, yy = np.mgrid[0:5:.1, 0:5:.1] probs = np.zeros(xx.shape) for k in range(3): for i in range(xx.shape[0]): for j in range(xx.shape[1]): probs[i, j] = self.predict([xx[i, j], yy[i, j]])[k] plt.contour(xx, yy, probs, levels=[0.5])
def plot_contour(self): X, Y = np.meshgrid(np.arange(-1.00, 1.01, 2./(len(self.lattice_in) - 1)), np.arange(-1.00, 1.01, 2./(len(self.lattice_in) - 1))) plt.figure(figsize = (8,8)) CS = plt.contour(X, Y, self.lattice_in, 19) plt.clabel(CS, inline=1, fontsize=10) plt.title('Electric potential near two metal plates') #plt.show() return 0
def contour(self, *args, **kwargs): defaults = {'origin': 'lower', 'cmap': plt.cm.Greys, 'levels': np.sort(self.nice_levels())} defaults.update(**kwargs) ax = kwargs.pop('ax', plt.gca()) return ax.contour(self.im.T, *args, extent=self.e, **defaults)
def plot(self, contour={}, scatter={}, **kwargs): # levels = np.linspace(self.im.min(), self.im.max(), 10)[1:] levels = self.nice_levels() c_defaults = {'origin': 'lower', 'cmap': plt.cm.Greys_r, 'levels': levels} c_defaults.update(**contour) c = self.contourf(**c_defaults) lvls = np.sort(c.levels) s_defaults = {'c': '0.0', 'edgecolor':'None', 's':2} s_defaults.update(**scatter) self.scatter(lvl=[lvls], **s_defaults)
def contour(first, *args, **kwargs): """ Wrapper around matplotlib.pyplot.contour that also takes TH2 see mplbplot.draw_th2.contour or matplotlib.pyplot.contour for details """ if isinstance(first, gbl.TH2): kwargs["axes"] = plt.gca() return draw_th2.contour(first, *args, **kwargs) else: return plt.contour(first, *args, **args)
def Output(): x1 = np.linspace(0, 0.85, 1e2) x2 = np.linspace(0, 0.55, 1e2) x1, x2 = pl.meshgrid(x1, x2) plt.figure(figsize = (20, 15)) for id, item in enumerate(traits): plt.scatter(item[0], item[1], c = 'r' if judge[id] == 1.0 else 'b', s = 200, marker = 'o') plt.contour(x1, x2, f(x1, x2), 0) plt.show() plt.savefig("MMMMMMMua.png", dpi = 300)
def Contour(obj, pcolor=False, contour=True, imshow=False, **options): """Makes a contour plot. d: map from (x, y) to z, or object that provides GetDict pcolor: boolean, whether to make a pseudocolor plot contour: boolean, whether to make a contour plot imshow: boolean, whether to use pyplot.imshow options: keyword args passed to pyplot.pcolor and/or pyplot.contour """ try: d = obj.GetDict() except AttributeError: d = obj _Underride(options, linewidth=3, cmap=matplotlib.cm.Blues) xs, ys = zip(*d.keys()) xs = sorted(set(xs)) ys = sorted(set(ys)) X, Y = np.meshgrid(xs, ys) func = lambda x, y: d.get((x, y), 0) func = np.vectorize(func) Z = func(X, Y) x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False) axes = pyplot.gca() axes.xaxis.set_major_formatter(x_formatter) if pcolor: pyplot.pcolormesh(X, Y, Z, **options) if contour: cs = pyplot.contour(X, Y, Z, **options) pyplot.clabel(cs, inline=1, fontsize=10) if imshow: extent = xs[0], xs[-1], ys[0], ys[-1] pyplot.imshow(Z, extent=extent, **options)
def Contour(obj, pcolor=False, contour=True, imshow=False, **options): """Makes a contour plot. d: map from (x, y) to z, or object that provides GetDict pcolor: boolean, whether to make a pseudocolor plot contour: boolean, whether to make a contour plot imshow: boolean, whether to use plt.imshow options: keyword args passed to plt.pcolor and/or plt.contour """ try: d = obj.GetDict() except AttributeError: d = obj _Underride(options, linewidth=3, cmap=matplotlib.cm.Blues) xs, ys = zip(*d.keys()) xs = sorted(set(xs)) ys = sorted(set(ys)) X, Y = np.meshgrid(xs, ys) func = lambda x, y: d.get((x, y), 0) func = np.vectorize(func) Z = func(X, Y) 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) if imshow: extent = xs[0], xs[-1], ys[0], ys[-1] plt.imshow(Z, extent=extent, **options)
def show_2D_GPSA(raw, GPSA_data_list, key_x='axis0', key_y='axis1', clim=None, cmap='jet', mutiplier=1.0, Z_cut=None, Z_contour=([],[]), ): x = raw[key_x] y = raw[key_y] Z = raw['mixture fraction'] xx = sorted(list(set(x))) yy = sorted(list(set(y))) n_x = len(xx) n_y = len(yy) print 'n_x = '+str(n_x) print 'n_y = '+str(n_y) if n_x*n_y == 0: print 'cannot build as n_x = '+str(n_x)+', n_y = '+str(n_y) print 'raw = '+str(raw) return print 'building matrix' data = np.zeros((n_y,n_x)) Zmat = np.zeros((n_y,n_x)) for i in range(len(x)): i_y = yy.index(y[i]) i_x = xx.index(x[i]) #if raw['active species'][i]>5: if Z_cut is not None and Z[i]<Z_cut: data[i_y, i_x] = float('nan') else: data[i_y, i_x] = GPSA_data_list[i] * mutiplier Zmat[i_y, i_x] = Z[i] print 'plotting' colors = ['k','w'] lw = [1,3] if len(Z_contour)>0: for i_v in range(len(Z_contour)): CS = plt.contour(Zmat, [Z_contour[0][i_v]], colors=colors[i_v], linewidths=lw[i_v]) #plt.clabel(CS, fontsize=10, inline=1, fmt=Z_contour[1][i_v]) #plt.legend(Z_contour[1]) #imsave(key_show+'.png',data) if clim is None: plt.imshow(data, cmap=cmap) else: plt.imshow(data, clim=clim, cmap=cmap) plt.colorbar() #plt.show()
def draw_contour(fn, bounds, nodes=None, points=None, title=None, **options): """Plot a contour of a function. Experimental, only 2D supported. Parameters ---------- fn : callable bounds : list[arraylike] Bounds for the plot, e.g. [(0, 1), (0,1)]. nodes : list[str], optional points : arraylike, optional Additional points to plot. title : str, optional """ ax = get_axes(**options) x, y = np.meshgrid(np.linspace(*bounds[0]), np.linspace(*bounds[1])) z = fn(np.c_[x.reshape(-1), y.reshape(-1)]) if ax: plt.sca(ax) plt.cla() if title: plt.title(title) try: plt.contour(x, y, z.reshape(x.shape)) except ValueError: logger.warning('Could not draw a contour plot') if points is not None: plt.scatter(points[:-1, 0], points[:-1, 1]) if options.get('interactive'): plt.scatter(points[-1, 0], points[-1, 1], color='r') plt.xlim(bounds[0]) plt.ylim(bounds[1]) if nodes: plt.xlabel(nodes[0]) plt.ylabel(nodes[1])
def plot(self, logpdf=False): """Plot the posterior pdf. Currently only supports 1 and 2 dimensional cases. Parameters ---------- logpdf : bool Whether to plot logpdf instead of pdf. """ if logpdf: fun = self.logpdf else: fun = self.pdf with np.warnings.catch_warnings(): np.warnings.filterwarnings('ignore') if len(self.model.bounds) == 1: mn = self.model.bounds[0][0] mx = self.model.bounds[0][1] dx = (mx - mn) / 200.0 x = np.arange(mn, mx, dx) pd = np.zeros(len(x)) for i in range(len(x)): pd[i] = fun([x[i]]) plt.figure() plt.plot(x, pd) plt.xlim(mn, mx) plt.ylim(min(pd) * 1.05, max(pd) * 1.05) plt.show() elif len(self.model.bounds) == 2: x, y = np.meshgrid( np.linspace(*self.model.bounds[0]), np.linspace(*self.model.bounds[1])) z = (np.vectorize(lambda a, b: fun(np.array([a, b]))))(x, y) plt.contour(x, y, z) plt.show() else: raise NotImplementedError("Currently unsupported for dim > 2")
def plot_validate_bivariate(data_true_a, data_true_b, data_predicted_a, data_predicted_b, n_bins, xlab, ylab, name, x_range, y_range, legend=False): H_true, xedges_true, yedges_true = np.histogram2d(data_true_a + np.random.normal(0,0.4,data_true_a.shape), data_true_b + np.random.normal(0,0.4,data_true_b.shape), range=[x_range, y_range], bins=n_bins) H_true = H_true/H_true.sum() H_predicted, xedges_predicted, yedges_predicted = np.histogram2d(data_predicted_a + np.random.normal(0,0.4,data_predicted_a.shape), data_predicted_b + np.random.normal(0,0.4,data_predicted_b.shape), range=[x_range, y_range], bins=n_bins) H_predicted = H_predicted/H_predicted.sum() extent_true = [yedges_true[0], yedges_true[-1], xedges_true[0], xedges_true[-1]] extent_predicted = [yedges_predicted[0], yedges_predicted[-1], xedges_predicted[0], xedges_predicted[-1]] plt.figure(num=None, figsize=(8, 6), dpi=150, facecolor='w', edgecolor='w') levels = (0.0001, 0.0005, 0.001, 0.005, 0.01, 0.015, 0.02) plt.contour(H_true, levels, origin='lower', colors=['green'], linewidths=(1, 1, 1, 1, 1, 1, 1),linestyles=['solid'],extent=extent_true,label="Actual Data") plt.contour(H_predicted, levels, origin='lower', colors=['brown'],linestyles=['dashed'], linewidths=(1, 1, 1, 1, 1, 1, 1), extent=extent_predicted,label = "Simulated Data") leg1, = plt.plot([],[], label="Actual Data", color="green") leg2, = plt.plot([],[], label="Simulated Data", color="brown", linestyle='dashed') if legend: plt.legend(handles=[leg1,leg2], fontsize=28) plt.tick_params(axis='both', which='major', labelsize=20) plt.tick_params(axis='both', which='minor', labelsize=20) plt.xlabel(ylab,fontsize=28, labelpad=15) plt.ylabel(xlab,fontsize=28, labelpad=15) plt.xlim(y_range[0], y_range[1]) plt.ylim(x_range[0], x_range[1]) plt.savefig(name, bbox_inches='tight') plt.close() # Compute ROC curve and ROC area for each class
def get_contours3d(A, dims, thr=0.9): """Gets contour of spatial components and returns their coordinates Parameters ----------- A: np.ndarray or sparse matrix Matrix of Spatial components (d x K) dims: tuple of ints Spatial dimensions of movie (x, y, z) thr: scalar between 0 and 1 Energy threshold for computing contours (default 0.995) Returns -------- Coor: list of coordinates with center of mass and contour plot coordinates (per layer) for each component """ d, nr = np.shape(A) d1, d2, d3 = dims x, y = np.mgrid[0:d2:1, 0:d3:1] coordinates = [] cm = np.asarray([center_of_mass(a.reshape(dims, order='F')) for a in A.T]) for i in range(nr): pars = dict() indx = np.argsort(A[:, i], axis=None)[::-1] cumEn = np.cumsum(A[:, i].flatten()[indx]**2) cumEn /= cumEn[-1] Bvec = np.zeros(d) Bvec[indx] = cumEn Bmat = np.reshape(Bvec, dims, order='F') pars['coordinates'] = [] for B in Bmat: cs = plt.contour(y, x, B, [thr]) # this fix is necessary for having disjoint figures and borders plotted correctly p = cs.collections[0].get_paths() v = np.atleast_2d([np.nan, np.nan]) for pths in p: vtx = pths.vertices num_close_coords = np.sum(np.isclose(vtx[0, :], vtx[-1, :])) if num_close_coords < 2: if num_close_coords == 0: # case angle newpt = np.round(vtx[-1, :] / [d2, d1]) * [d2, d1] vtx = np.concatenate((vtx, newpt[np.newaxis, :]), axis=0) else: # case one is border vtx = np.concatenate((vtx, vtx[0, np.newaxis]), axis=0) v = np.concatenate((v, vtx, np.atleast_2d([np.nan, np.nan])), axis=0) pars['coordinates'] += [v] pars['CoM'] = np.squeeze(cm[i, :]) pars['neuron_id'] = i + 1 coordinates.append(pars) return coordinates
def save_contour(netD, filename, cuda=False): #import warnings #warnings.filterwarnings("ignore", category=FutureWarning) #import numpy as np #import matplotlib #matplotlib.use('Agg') #import matplotlib.cm as cm #import matplotlib.mlab as mlab #import matplotlib.pyplot as plt matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'out' matplotlib.rcParams['contour.negative_linestyle'] = 'solid' # gen grid delta = 0.1 x = np.arange(-25.0, 25.0, delta) y = np.arange(-25.0, 25.0, delta) X, Y = np.meshgrid(x, y) # convert numpy array to to torch variable (h, w) = X.shape XY = np.concatenate((X.reshape((h*w, 1, 1, 1)), Y.reshape((h*w, 1, 1, 1))), axis=1) input = torch.Tensor(XY) input = Variable(input) if cuda: input = input.cuda() # forward output = netD(input) # convert torch variable to numpy array Z = output.data.cpu().view(-1).numpy().reshape(h, w) # plot and save plt.figure() CS1 = plt.contourf(X, Y, Z) CS2 = plt.contour(X, Y, Z, alpha=.7, colors='k') plt.clabel(CS2, inline=1, fontsize=10, colors='k') plt.title('Simplest default with labels') plt.savefig(filename) plt.close()
def plot_model(model, data): """ :param model: the GMM model :param data: the data set 2D :return: """ delta = 0.025 x = np.arange(0.0, 4, delta) y = np.arange(0.0, 4, delta) X, Y = np.meshgrid(x, y) z = np.zeros((np.size(x), np.size(y))) # sum of Gaussian plt.figure() for i in range(np.size(model)): ztemp = mlab.bivariate_normal(X, Y, np.sqrt(model['cov'][i][0, 0]), np.sqrt(model['cov'][i][1, 1]), model['mu'][i][0], model['mu'][i][1], model['cov'][i][0,1]) plt.contour(X, Y, model['w'][i]*ztemp) z = np.add(z, ztemp) plt.scatter(data[0, :], data[1, :], s=5) plt.figure() plt.contour(X, Y, z) plt.scatter(data[0, :], data[1, :], s=5)