def plot(self, N=6, cm=plt.cm.jet): plt.figure() plt.gca().set_aspect('equal') plt.tricontourf(self.triang, self.density, N, cm=cm) plt.colorbar() plt.tricontour(self.triang, self.density, N, colors='k') plt.show()
def plot(filename): import os from matplotlib.pyplot import clf, tricontour, tricontourf, \ gca, savefig, rc, minorticks_on if not os.path.exists(filename): return -1 rc('text', usetex=True) clf() x, y, tri, ux, uy = load_velocity(filename) tricontourf(x, y, tri, ux, 16) tricontour(x, y, tri, ux, 16, linestyles='-', colors='black', linewidths=0.5) minorticks_on() gca().set_aspect('equal') gca().tick_params(direction='out', which='both') gca().set_xticklabels([]) gca().set_yticklabels([]) name, _ = os.path.splitext(filename) name = os.path.basename(name) savefig('{0}.png'.format(name), dpi=300, bbox_inches='tight') savefig('{0}.pdf'.format(name), bbox_inches='tight')
def contour(data, x, y, label=None, log=False): tri=Triangulation(x,y) plt.close('all') plt.figure() ax=plt.subplot(111) ax.minorticks_on() if(log): ax.set_xscale("log",nonposx='clip') ax.set_yscale("log",nonposy='clip') ax.set_xlim([min(x.min(),y.min()),max(x.max(),y.max())]) ax.set_ylim([min(x.min(),y.min()),max(x.max(),y.max())]) plt.xlabel('r [AU]') plt.ylabel('z [AU]') nmax=data.max() nmin=data.min() levels=np.logspace(np.log10(nmin),np.log10(nmax),num=12) plt.tricontourf(tri, data, levels, norm=colors.LogNorm(vmin=nmin, vmax=nmax)) cbar=plt.colorbar(format='%.2e') cbar.set_label(label) CS=plt.tricontour(tri, data, levels, colors='black', linewidths=1.5) plt.clabel(CS, fontsize=8, inline=1) cbar.add_lines(CS) plt.triplot(tri, color='black', alpha=0.2) plt.show(block=False)
def graph_grid(self, debug=False): ''' 2D xy plot of bathymetry and mesh. No inputs required so far''' if debug or self._debug: print 'Plotting grid...' nv = self._var.nv.T -1 h = self._var.h tri = Tri.Triangulation(self._var.lon, self._var.lat, triangles=nv) levels=np.arange(-100,-4,1) # depth contours to plot fig = plt.figure(figsize=(18,10)) plt.rc('font',size='22') ax = fig.add_subplot(111,aspect=(1.0/np.cos(np.mean(self._var.lat)*np.pi/180.0))) plt.tricontourf(tri, -h,levels=levels,shading='faceted',cmap=plt.cm.gist_earth) plt.triplot(tri) plt.ylabel('Latitude') plt.xlabel('Longitude') plt.gca().patch.set_facecolor('0.5') cbar=plt.colorbar() cbar.set_label('Water Depth (m)', rotation=-90,labelpad=30) scale = 1 ticks = ticker.FuncFormatter(lambda lon, pos: '{0:g}'.format(lon/scale)) ax.xaxis.set_major_formatter(ticks) ax.yaxis.set_major_formatter(ticks) plt.grid() plt.show() if debug or self._debug: print '...Passed'
def my_plot(u,v,t,daystr,levels): #boston light swim ax= [-71.10, -70.10, 41.70, 42.70] # region to plot vel_arrow = 0.2 # velocity arrow scale subsample = 8 # subsampling of velocity vectors # find velocity points in bounding box ind = np.argwhere((lonc >= ax[0]) & (lonc <= ax[1]) & (latc >= ax[2]) & (latc <= ax[3])) np.random.shuffle(ind) Nvec = int(len(ind) / subsample) idv = ind[:Nvec] # tricontourf plot of water depth with vectors on top plt.figure(figsize=(20,10)) plt.subplot(111,aspect=(1.0/np.cos(lat[:].mean()*np.pi/180.0))) #tricontourf(tri, t,levels=levels,shading='faceted',cmap=plt.cm.gist_earth) plt.tricontourf(tri, t,levels=levels,shading='faceted') plt.axis(ax) plt.gca().patch.set_facecolor('0.5') cbar=plt.colorbar() cbar.set_label('Forecast Surface Temperature (C)', rotation=-90) plt.tricontour(tri, t,levels=[0]) Q = plt.quiver(lonc[idv],latc[idv],u[idv],v[idv],scale=10) maxstr='%3.1f m/s' % vel_arrow qk = plt.quiverkey(Q,0.92,0.08,vel_arrow,maxstr,labelpos='W') plt.title('NECOFS Surface Velocity, Layer %d, %s UTC' % (ilayer, daystr)) plt.plot(lon_track,lat_track,'m-o') plt.plot(lon_buoy,lat_buoy,'y-o')
def draw_pdf_contours(dist, border=False, nlevels=200, subdiv=8, **kwargs): '''Draws pdf contours over an equilateral triangle (2-simplex). Arguments: `dist`: A distribution instance with a `pdf` method. `border` (bool): If True, the simplex border is drawn. `nlevels` (int): Number of contours to draw. `subdiv` (int): Number of recursive mesh subdivisions to create. kwargs: Keyword args passed on to `plt.triplot`. ''' from matplotlib import ticker, cm import math refiner = tri.UniformTriRefiner(_triangle) trimesh = refiner.refine_triangulation(subdiv=subdiv) pvals = [dist.pdf(xy2bc(xy)) for xy in zip(trimesh.x, trimesh.y)] plt.tricontourf(trimesh, pvals, nlevels, **kwargs) plt.axis('equal') plt.xlim(0, 1) plt.ylim(0, 0.75**0.5) plt.axis('off') if border is True: plt.hold(1) plt.triplot(_triangle, linewidth=1)
def isosurf(G,Z,titre): """ trace isosurface de Z sur le maillage G""" triang=tri.Triangulation(G.X[:,0],G.X[:,1],triangles=G.Tbc) plt.tricontourf(triang, Z) plt.colorbar() plt.title(titre) return
def fcontour_plot_dataset(file_path,hdf_file_name,x_variable,y_variable,z_variable, clims=None,num_levels=41): '''Script to make a contour plot of a dataset from an HDF5 files of several scans combined. ''' #Create a new figure plt.figure() plt.suptitle(hdf_file_name) #Open file hdf_file = h5py.File(file_path + hdf_file_name,'r') #Mask off any NAN entries is x; indicates scan wasn't as wide as widest scan mask = np.isfinite(hdf_file[x_variable]) #Make triangulation for Delauney triangulation plot triang = tri.Triangulation(hdf_file[x_variable][mask], hdf_file[y_variable][mask]) #Create contour plot if clims: contour_levels = np.linspace(clims[0],clims[1],num_levels) plt.tricontourf(triang,hdf_file[z_variable][mask],contour_levels,extend='both') else: plt.tricontourf(triang,hdf_file[z_variable][mask],num_levels,extend='both') plt.xlabel(x_variable) plt.ylabel(y_variable) cb = plt.colorbar() cb.ax.set_ylabel(z_variable) plt.show()
def testSquare(): ptlist = { "vertices": np.array( ((0.0, 0.0), (0.5, 0.0), (1.0, 0.0), (0.0, 0.5), (0.5, 0.5), (1.0, 0.5), (0.0, 1.0), (0.5, 1.0), (1.0, 1.0)) ) } t = triangle.triangulate(ptlist) t1 = triangle.triangulate(ptlist, "qa0.001") triangle.plot.compare(plt, t, t1) # plt.show() L, M = FE.assembleMatrices(t) # print L # print '\n\n' # print M np.savetxt("textL", L) np.savetxt("textM", M) eig = FE.eigenvalues(L, M) elist = eig[0] efunc = eig[1] print elist[0] print elist[1] print elist[2] # vertices = np.asarray(t['vertices']) # faces = np.asarray(t['triangles']) # x = vertices[:,0] # y = vertices[:,1] # z = efunc[1] # plt.figure() # plt.tricontourf(x,y,faces,z,cmap='afmhot') # plt.show() print "****************************" L, M = FE.assembleMatrices(t1) eig = FE.eigenvalues(L, M) elist = eig[0] efunc = eig[1] for j in range(10): print elist[j] vertices = np.asarray(t1["vertices"]) faces = np.asarray(t1["triangles"]) x = vertices[:, 0] y = vertices[:, 1] z = efunc[:, 5] plt.figure() plt.tricontourf(x, y, z, 100, cmap="afmhot") plt.show() print "***************************\n\n\n\n\n"
def show_data_domain_2D(samples, data, Q_ref, ref_markers=None, ref_colors=None, xlabel=r'$q_1$', ylabel=r'$q_2$', triangles=None, save=True, interactive=False, filenames=None): r""" Plot the data domain D using a triangulation based on the generating samples with a marker for various :math:`Q_{ref}`. Assumes that the first dimension of data is :math:`q_1`. :param samples: Samples to plot :type samples: :class:`~numpy.ndarray` of shape (num_samples, ndim) :param data: Data associated with ``samples`` :type data: :class:`numpy.ndarray` :param Q_ref: reference data value :type Q_ref: :class:`numpy.ndarray` of shape (M, 2) :param list ref_markers: list of marker types for :math:`Q_{ref}` :param list ref_colors: list of colors for :math:`Q_{ref}` :param string xlabel: x-axis label :param string ylabel: y-axis label :param triangles: triangulation defined by ``samples`` :type triangles: :class:`tri.Triuangulation.triangles` :param bool save: flag whether or not to save the figure :param bool interactive: flag whether or not to show the figure :param list filenames: file names for the unmarked and marked domain plots """ if ref_markers == None: ref_markers = markers if ref_colors == None: ref_colors = colors if type(triangles) == type(None): triangulation = tri.Triangulation(samples[:, 0], samples[:, 1]) triangles = triangulation.triangles if filenames == None: filenames = ['domain_q1_q2_cs.eps', 'q1_q2_domain_Q_cs.eps'] Q_ref = util.fix_dimensions_data(Q_ref, 2) # Create figure plt.tricontourf(data[:, 0], data[:, 1], np.zeros((data.shape[0],)), triangles=triangles, colors='grey') plt.autoscale(tight=True) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.savefig(filenames[0], bbox_inches='tight', transparent=True, pad_inches=0) # Add truth markers for i in xrange(Q_ref.shape[0]): plt.scatter(Q_ref[i, 0], Q_ref[i, 1], s=60, c=ref_colors[i], marker=ref_markers[i]) if save: plt.savefig(filenames[1], bbox_inches='tight', transparent=True, pad_inches=0) if interactive: plt.show() else: plt.close()
def graphGrid(self,narrowGrid=False, plot=False): #nx.draw(self.graph, self.pointIDXY) #plt.show() #lat = self.data.variables['lat'][:] #lon = self.data.variables['lon'][:] #nv = self.data.variables['nv'][:].T -1 #h = self.data.variables['h'][:] lat = self.lat lon = self.lon nv = self.nv.T - 1 h = self.h tri = Tri.Triangulation(lon, lat, triangles=nv) # xy or latlon based on how you are #Grand Passage levels=np.arange(-38,6,1) # depth contours to plot fig = plt.figure(figsize=(18,10)) plt.rc('font',size='22') ax = fig.add_subplot(111,aspect=(1.0/np.cos(np.mean(lat)*np.pi/180.0))) plt.tricontourf(tri, -h,levels=levels,shading='faceted',cmap=plt.cm.gist_earth) plt.triplot(tri) plt.ylabel('Latitude') plt.xlabel('Longitude') plt.gca().patch.set_facecolor('0.5') cbar=plt.colorbar() cbar.set_label('Water Depth (m)', rotation=-90,labelpad=30) scale = 1 ticks = ticker.FuncFormatter(lambda lon, pos: '{0:g}'.format(lon/scale)) ax.xaxis.set_major_formatter(ticks) ax.yaxis.set_major_formatter(ticks) plt.grid() maxlat, maxlon = np.max(self.maxcoordinates,axis=0) minlat, minlon = np.min(self.mincoordinates,axis=0) if narrowGrid: ax.set_xlim(minlon,maxlon) ax.set_ylim(minlat,maxlat) zz = len(self.elements) for i,v in enumerate(self.elements): source = self.pointIDXY[v[0]] target = self.pointIDXY[v[-1]] lab = '({:.6},{:.6})-({:.6},{:.6})'.format(source[0], source[1], target[0], target[1]) plt.scatter(self.lonc[v], self.latc[v], s=80, label=lab, c=plt.cm.Set1(i/zz)) #plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=2, ncol=3,fontsize='14', borderaxespad=0.) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=2, ncol=3) #plt.legend() if plot: plt.show()
def get_SMC_plot(age): sfr = np.array([]) for i in np.arange(len(smc_coor)): sfr = np.append(sfr, get_SFH(smc_coor["ra"][i], \ smc_coor["dec"][i], age, smc_coor, smc_sfh)) plt.tricontourf(smc_coor["ra"], smc_coor["dec"], sfr) plt.title(str(int(age)) + ' Myr') return plt
def contourf(*arguments, **kwargs): """Call signatures:: contourf(X, Y, C, N, **kwargs) contourf(X, Y, C, V, **kwargs) Create a contourf plot of a 2-D llc array (with tricontour). *C* is the array of color values. *N* is the number of levels *V* is a list of levels *X* and *Y*, specify the (*x*, *y*) coordinates of the grid points **kwargs are passed to tricontour. """ arglen = len(arguments) h = [] if arglen >= 3: data = np.copy(arguments[2].flatten()) x = arguments[0].flatten() y = arguments[1].flatten() # Create the Triangulation; # no triangles so Delaunay triangulation created. triang = tri.Triangulation(x, y) ntri = triang.triangles.shape[0] # Mask off unwanted triangles. mask = np.where(data[triang.triangles].prod(axis=1)==0., 1, 0) triang.set_mask(mask) if arglen == 3: h = plt.tricontourf(triang, data, **kwargs) elif arglen == 4: h = plt.tricontourf(triang, data, arguments[3], **kwargs) else: print("wrong number of arguments") print("need at least 3 or 4 arguments") sys.exit(__doc__) # show the triangles for debugging #plt.triplot(triang, color='0.7') else: print("wrong number of arguments") print("need at least x,y,fld") sys.exit(__doc__) return h
def isosurf(self,Z,titre,front=True): """ trace isosurface de Z sur le maillage G""" triang=tri.Triangulation(self.X[:,0],self.X[:,1],triangles=self.Tbc) plt.tricontourf(triang, Z) if front: ARF=self.arfront() for L in ARF: plt.plot(self.X[L,0],self.X[L,1],lw=2,color='k') plt.colorbar() plt.title(titre) return
def get_LMC_plot(age): sfr = np.array([]) for i in np.arange(len(lmc_coor)): sfr = np.append(sfr, get_SFH(lmc_coor["ra"][i], \ lmc_coor["dec"][i], age, lmc_coor, lmc_sfh)) plt.tricontourf(lmc_coor["ra"], lmc_coor["dec"], sfr) plt.title(str(int(age)) + ' Myr') plt.ylim(-73, -64) return plt
def graphGrid(self,narrowGrid=False, plot=False): ''' A method to graph the grid with the shortest path plotted on the grid. narrowGrid will limit the field of view down to only show the paths drawn and not the entire grid. If only one path is drawn, this can skew the way the grid looks, and is sometime better to view the whole grid and zoom in. The plot option is in cause you want to choose when to plot the graph in a different part of the code.''' lat = self.lat lon = self.lon nv = self.nv.T - 1 h = self.h tri = Tri.Triangulation(lon, lat, triangles=nv) # xy or latlon based on how you are #Grand Passage levels=np.arange(-38,6,1) # depth contours to plot fig = plt.figure(figsize=(18,10)) plt.rc('font',size='22') ax = fig.add_subplot(111,aspect=(1.0/np.cos(np.mean(lat)*np.pi/180.0))) plt.tricontourf(tri, -h,levels=levels,shading='faceted',cmap=plt.cm.gist_earth) plt.triplot(tri) plt.ylabel('Latitude') plt.xlabel('Longitude') plt.gca().patch.set_facecolor('0.5') cbar=plt.colorbar() cbar.set_label('Water Depth (m)', rotation=-90,labelpad=30) scale = 1 ticks = ticker.FuncFormatter(lambda lon, pos: '{0:g}'.format(lon/scale)) ax.xaxis.set_major_formatter(ticks) ax.yaxis.set_major_formatter(ticks) plt.grid() maxlat, maxlon = np.max(self.maxcoordinates,axis=0) minlat, minlon = np.min(self.mincoordinates,axis=0) if narrowGrid: ax.set_xlim(minlon,maxlon) ax.set_ylim(minlat,maxlat) zz = len(self.elements) for i,v in enumerate(self.elements): source = self.pointIDXY[v[0]] target = self.pointIDXY[v[-1]] lab = '({:.6},{:.6})-({:.6},{:.6})'.format(source[0], source[1], target[0], target[1]) plt.scatter(self.lonc[v], self.latc[v], s=80, label=lab, c=plt.cm.Set1(i/zz)) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=2, ncol=3) if plot: plt.show()
def _add_obj_contour(x,y,color,label,columns,data,theta_star): ax = plt.gca() xvar, yvar, loc = _get_variables(ax,columns) try: X, Y, Z = _get_data_slice(xvar,yvar,columns,data,theta_star) triang = tri.Triangulation(X, Y) cmap = plt.cm.get_cmap('Greys') plt.tricontourf(triang,Z,cmap=cmap) except: print('Objective contour plot for', xvar, yvar,'slice failed')
def draw_pdf_contours(dist, nlevels=200, subdiv=8, **kwargs): import math refiner = tri.UniformTriRefiner(triangle) trimesh = refiner.refine_triangulation(subdiv=subdiv) pvals = [dist.pdf(xy2bc(xy)) for xy in zip(trimesh.x, trimesh.y)] plt.tricontourf(trimesh, pvals, nlevels, **kwargs) plt.axis('equal') plt.xlim(0, 1) plt.ylim(0, 0.75**0.5) plt.axis('off')
def PlotAutocorrelations(system,shifts=[],update_datafiles=True,all_windows=True): outdir=_OutputDir(system) if update_datafiles:system.UpdateDataFiles(new_only=False) for w in system.windows: if (not all_windows) and hasattr(w,"auto_correlation_times"):continue t,cvs=w.ReadDataFile() ndata=len(t) if not shifts: dts=[] for i in range(ndata): dt=2**i if dt<ndata:dts.append(dt) else:break else: dts=[el for el in shifts if el<ndata] auto_corr_times=[] for i,cv in enumerate(cvs): cv=npy.array(cv) cl=[] for dt in dts:cl.append(npy.corrcoef(cv[:-dt],cv[dt:])[0,1]) bools=npy.array(cl)<0.1 auto_corr_time=dts[-1] for j in range(len(dts)-1,-1,-1): if not bools[j]:break auto_corr_time=dts[j] plt.figure() plt.plot(dts,cl,'-o') plt.xlim([1,dts[-1]+1]) plt.xscale("log") plt.xlabel("Time shift") plt.ylabel("Autocorrelation") plt.title("Autocorr for {0} for window {1}:{2}".format(system.cv_list[i].name,w.name,auto_corr_time)) plt.savefig(os.path.join(outdir,"{0}_{1}_autocorr.png".format(w.name,system.cv_list[i].name))) plt.close() auto_corr_times.append(auto_corr_time) w.auto_correlation_times=auto_corr_times cv1=[] cv2=[] auto_corr=[] for w in system.windows: cv1.append(w.cv_values[0]) cv2.append(w.cv_values[1]) auto_corr.append(npy.log10(npy.max(w.auto_correlation_times))) plt.figure() plt.tricontourf(cv1,cv2,auto_corr, 20) plt.xlabel(system.cv_list[0].name+" "+system.cv_list[0].units) plt.ylabel(system.cv_list[1].name+" "+system.cv_list[1].units) cbar=plt.colorbar() cbar.set_label("log10 decorrelation time", rotation=270) plt.title("Decorrelation times") plt.savefig(os.path.join(outdir,"decorrelation_times.png")) plt.close() return
def fcontour_plot_dataset(file_path,hdf_file_name,x_variable,y_variable,z_variable, grid_on = False,**kwargs): '''Script to make a contour plot of a dataset from an HDF5 file of several scans combined. Keyword arguments are either captured by this code or sent to the tricontourf function. Keywords handled by this code: z_scale: multiplicative factor by with the z variable is multiplied. title: title to put at the top of the figure xlims,ylims: set limits on x and y extent of the figure cticks: set colorbar ticks ctick_labels: set labels on the colorbar ticks z_label: label for the colorbar axis. Defaults to z_variable ''' #Create a new figure plt.figure(figsize=[4,3],dpi=300) if 'title' in kwargs.keys(): plt.suptitle(kwargs['title']) plt.grid(grid_on) #Tune the size plt.subplots_adjust(left=0.2,right=0.82,bottom = 0.15, top = 0.95) #Add in a multipliciative factor, if requested z_scale = 1. if 'z_scale' in kwargs.keys(): z_scale = float(kwargs['z_scale']) #Open file with h5py.File(file_path + hdf_file_name,'r') as hdf_file: #Mask off any NAN entries is x; indicates scan wasn't as wide as widest scan mask = np.isfinite(hdf_file[x_variable]) #Make triangulation for Delauney triangulation plot triang = tri.Triangulation(hdf_file[x_variable][mask], hdf_file[y_variable][mask]) #Create contour plot plt.tricontourf(triang,hdf_file[z_variable][mask]*z_scale,**kwargs) plt.xlabel(x_variable) plt.ylabel(y_variable) if 'xlims' in kwargs.keys(): plt.xlim(kwargs['xlims']) if 'ylims' in kwargs.keys(): plt.ylim(kwargs['ylims']) cb = plt.colorbar() cb.ax.tick_params(labelsize=12) if 'cticks' in kwargs.keys(): cb.set_ticks(kwargs['cticks']) if 'z_label' in kwargs.keys(): cb.ax.set_ylabel(kwargs['z_label']) if 'ctick_labels' in kwargs.keys(): cb.ax.set_yticklabels(kwargs['ctick_labels']) else: cb.ax.set_ylabel(z_variable)
def operateInternal(self): # Access the mesh and filename from the parameters mesh = self.parameters().find('mesh').value(0) filename = self.parameters().find('filename').value(0) # Collect point coordinates coords = [] class GetPoints(smtk.mesh.PointForEach): def __init__(self): smtk.mesh.PointForEach.__init__(self) def forPoints(self, pointIds, xyz, doModify): for pId in range(pointIds.size()): coords.insert(pId, [xyz[3 * pId + i] for i in range(3)]) getPoints = GetPoints() smtk.mesh.for_each(mesh.points(), getPoints) # Collect triangles tris = [] class GetTriangles(smtk.mesh.CellForEach): def __init__(self): smtk.mesh.CellForEach.__init__(self, False) def forCell(self, cellId, cellType, numPoints): if numPoints == 3: tris.append( [mesh.points().find(self.pointId(i)) for i in range(numPoints)]) getTriangles = GetTriangles() smtk.mesh.for_each(mesh.cells(), getTriangles) # Construct a pyplot, populate it with the triangles and color it by the # z-coordinate of the mesh plt.figure(figsize=(3, 2), dpi=100) plt.tricontourf([c[0] for c in coords], [c[1] for c in coords], tris, [c[2] for c in coords]) plt.colorbar() plt.title('Mesh Elevation') plt.xlabel('X (units)') plt.ylabel('Y (units)') # Save the resulting image to the user-defined filename plt.savefig(filename, bbox_inches='tight') # Return with success result = self.createResult(smtk.operation.Operation.Outcome.SUCCEEDED) return result
def stab_plot(self): x = self.x y = self.y z = self.z # initialize the delauney triangulation: triang = tri.Triangulation(x, y) # do the plots: plt.tricontourf(triang, z, colors=self.color, alpha=0.3, levels=[1.0, 2.0]) plt.tricontour(triang, z, colors=self.color, levels=[1.0, 2.0]) # title of the plot plt.title("Stability of " + self.model_name, fontsize=16) # labels plt.xlabel(self.param_names[0], fontsize=18) plt.ylabel(self.param_names[1], fontsize=18)
def plotResult(self): x = [] y = [] z = [] for n in self.nodes: x.append(n.x) y.append(n.y) z.append(self.result[n.i-1]) t = tri.Triangulation(x, y) plt.tricontour(t, z, 15, linewidths=0.5, colors='k') plt.tricontourf(t, z, 15, cmap=plt.cm.rainbow) plt.plot(x, y, 'ko', ms=3) plt.colorbar()
def plot_contour( coordinates, values, space_dim= 2 ): assert space_dim == 2, 'only works for two space dim' x = coordinates[:,0] y = coordinates[:,1] # Create the Triangulation just for plotting triang = tri.Triangulation(x, y) # Plot contour plt.figure() plt.gca().set_aspect('equal') plt.tricontourf(triang, values) return
def frequency_map( self, frequency, orientation, component, ax=None, plot_error=True, **plot_kwargs): """ Function to generate a iso-frequency map :param numpy.ndarray frequency: Frequency to be mapped :param str orientation: The orientation of the data :param str component: The data component to plot :param matplotlib.axes ax (optional): :param matplotlib.lines.Line2D keyword_arguments plot_kwargs) """ # Sort the axes if ax is None: fig, ax = plt.subplots(1, 1) else: fig = ax.get_figure() # Plot the data locs, plot_data, errorbars = _get_map_data( self, frequency, orientation, component,plot_error) plot_obj = plt.tricontourf(locs, plot_data, **plot_kwargs) return (fig, ax, plot_obj)
def plt_geom(hatch_geom): """ Plot the 2D cross section of a hatch, showing: - Side view of hatch - Marked CG point in 2D projection - Hinge position, marked """ # Start with geometry fetching # May need to merge xyz vectors into node array first, in case we do any coord transformations pad_vec = np.ones(hatch_geom['x'].shape) hatch_geom['nodes'] = np.vstack((hatch_geom['x'], hatch_geom['y'], hatch_geom['z'], pad_vec)).T plt.figure() tr = Triangulation(hatch_geom['nodes'][:,0], this_geom['nodes'][:,1], triangles=this_geom['tris']) plt.tricontourf(tr, tr.x*0.0); plt.gca().set_aspect('equal') plt.show()
def plot_gain2D(self, n_pts=720, log_scale=True): """Plot the 2D gain pattern of an array.""" x_plot_min = self.x_min - 1000 x_plot_max = self.x_max + 1000 y_plot_min = self.y_min - 1000 y_plot_max = self.y_max + 1000 # Based on tricontourf example from # http://matplotlib.org/examples/pylab_examples/tricontour_demo.html n_angles = n_pts n_radii = 10 min_radius = 200 radii = np.linspace(min_radius, y_plot_max, n_radii) angles = np.linspace(-np.pi, np.pi, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += np.pi / n_angles x = (radii * np.cos(angles)).ravel() y = (radii * np.sin(angles)).ravel() z = self.gain_response(angles).ravel() # Roll so that 0 degrees is north z = np.roll(z, z.shape[0] / 4) if log_scale: z = 10 * np.log(z) triang = tri.Triangulation(x, y) xmid = x[triang.triangles].mean(axis=1) ymid = y[triang.triangles].mean(axis=1) mask = np.where(xmid * xmid + ymid * ymid < min_radius * min_radius, 1, 0) triang.set_mask(mask) ax = plt.gca() ax.set_aspect("equal") alpha = 0.8 plt.tricontourf(triang, z, cmap=plt.cm.Purples, alpha=alpha) plt.colorbar(alpha=alpha) self.plot_geometry() plt.xlim(x_plot_min, x_plot_max) plt.ylim(y_plot_min, y_plot_max) ax.patch.set_facecolor("white") ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) plt.setp(ax.get_xticklabels(), visible=False) plt.setp(ax.get_yticklabels(), visible=False)
def _plot_nut(t, nut): if nut is None: return print('Plotting nut ... ', end='') sys.stdout.flush() x = nut[:, 0] y = nut[:, 1] nut = nut[:, 3] plt.figure() plt.viridis() plt.tricontourf(x, y, nut / 15.11e-6, 64) plt.gca().set_aspect('equal') plt.colorbar(orientation='horizontal') plt.xlabel('x, m') plt.ylabel('y, m') plt.title(r'$\nu_t/\nu,\ t = {}\ s$'.format(t)) print('Done.') sys.stdout.flush() plt.savefig('nut.png', bbox_inches='tight', bbox_padding=0.5, dpi=150)
def bathymetry(domain, path=None, save=True, show=False, mesh = False, contour = False, ics=1, ext='.png', title=False): """ Given a domain, plot the bathymetry :param domain: :class:`~polyadcirc.run_framework.domain` :type path: string or None :param path: directory to store plots :type save: bool :param save: flag for whether or not to save plots :type show: bool :param show: flag for whether or not to show plots :type mesh: bool :param mesh: flag for whether or not to show mesh :param bool contour: use :meth:`~np.pyplot.tripcolor` or :meth:`~np.pyplot.tricontour` :param int ics: coordinate system (1 cartisian, 2 polar) :param string ext: file extesion """ z = domain.array_bathymetry() vmax = np.max(z) vmin = np.min(z) clim = (vmin, vmax) if path is None: path = os.getcwd() plt.figure() if mesh: plt.triplot(domain.triangulation, 'k-') if not contour: plt.tripcolor(domain.triangulation, z, shading='gouraud', cmap=plt.cm.ocean) else: plt.tricontourf(domain.triangulation, z, cmap=plt.cm.ocean) plt.gca().set_aspect('equal') add_2d_axes_labels(ics=ics) if clim: plt.clim(clim[0], clim[1]) if title: plt.title('bathymetry') colorbar() save_show(os.path.join(path, 'figs', 'bathymetry'), save, show, ext)
def plot_fem_function(file_path, plot_title, colorbar_max, nodes, elements, nodal_values): nodes_x = nodes[:, 0] nodes_y = nodes[:, 1] #=== Plot Mesh ===# # for element in elements: # x = [nodes_x[element[i]] for i in range(len(element))] # y = [nodes_y[element[i]] for i in range(len(element))] # plt.fill(x, y, edgecolor='black', fill=False) #=== Triangulate Mesh ===# triangulation = tri.Triangulation(nodes_x, nodes_y, elements) #=== Plot FEM Function ====# v = np.linspace(0, colorbar_max, 15, endpoint=True) plt.tricontourf(triangulation, nodal_values.flatten(), v) plt.colorbar(ticks=v) plt.axis('equal') plt.savefig(file_path) plt.close()
def plot(data,r,z,filename): points = np.transpose(np.array([z,r])) Delaunay_t = Delaunay(points) conn=Delaunay_t.simplices fig,ax=plt.subplots(figsize=(8,8)) plt.rc('xtick', labelsize=26) # fontsize of the tick labels plt.rc('ytick', labelsize=26) axis_font = {'fontname':'Arial', 'size':'38'} #plt.xlabel('R', **axis_font) #plt.ylabel('Z',**axis_font ) print len(r), len(z), len(conn), len(data) plt.tricontourf(r, z, conn, data,cmap=plt.cm.jet, levels=np.linspace(np.min(data),np.max(data),num=25)); #plt.colorbar(); plt.xticks([]) plt.yticks([]) for key, spine in ax.spines.items(): # 'left', 'right', 'bottom', 'top' if key == 'right' or key == 'top' or key == 'left' or key == 'bottom': spine.set_visible(False) plt.savefig(filename, format='png')
def ppi(self, elevation): AllInfo = [[], [], [], []] # 仰角 方位角 距离 反射率 for i in self.Storage: if elevation - 0.5 <= i[0][0] <= elevation + 0.5: # 设定仰角范围 for j in range(0, int(len(i[0][2]))): if 1: # 剔除反射率零点,以[0,0,0,0]代替以不影响矩阵形状 i[0][2][j] > 0 AllInfo[0].append(i[0][0]) # 仰角 #print(i[0][0]) AllInfo[1].append(i[0][1]) # 方位角 AllInfo[3].append(i[0][2][j]) # 反射率因子 AllInfo[2].append(i[0][3][j]) # 距离 AllInfo[0].append(0) AllInfo[1].append(0) AllInfo[2].append(0) AllInfo[3].append(75) while (len(AllInfo[0])) % 460 != 0: # 标准化为460倍数(补[0,0,0,0]法) AllInfo[0].append(0) AllInfo[1].append(0) AllInfo[2].append(0) AllInfo[3].append(0) Info_1 = np.array(AllInfo) x = Info_1[2] * np.cos(np.deg2rad(Info_1[0])) * np.cos( np.deg2rad(Info_1[1])) y = Info_1[2] * np.cos(np.deg2rad(Info_1[0])) * np.sin( np.deg2rad(Info_1[1])) z = Info_1[2] * np.sin(np.deg2rad(Info_1[0])) r = Info_1[3] plt.style.use('dark_background') plt.subplot(1, 1, 1) plt.title(self.Name) plt.tricontourf(x, y, r, cmap='jet') # contourf jet gray plt.colorbar() #plt.savefig('C:/data/gui/temp/ppi_ref/' + self.Name + '_ppi_' + str(elevation) + '.png', dpi = 300) #plt.close() plt.show()
def compute_diff(name, x, x_, datapath): assert (x.shape == x_.shape) plt.figure() trimesh = tri.Triangulation(r, z, conn) # plt.tricontourf(trimesh, np.mean(x, axis=(0,2,3))) # plt.axis('scaled') # plt.colorbar() # plt.savefig(name+'_ori.png') # plt.close() # plt.figure() # trimesh = tri.Triangulation(r, z, conn) # plt.tricontourf(trimesh, np.mean(x_, axis=(0,2,3))) # plt.axis('scaled') # plt.colorbar() # plt.savefig(name+'_rct.png') # plt.close() rel_err = relative_abs_error(x, x_) if (len(x.shape) == 4): gb_L_inf = np.max(rel_err, axis=(-1, -2)) index = np.argmax(gb_L_inf[0, :]) sort_err = np.argsort(gb_L_inf[0, :]) print(sort_err[:10]) else: gb_L_inf = rel_err index = np.argmax(gb_L_inf[0, :]) sort_err = np.argsort(gb_L_inf[0, :]) plt.figure() trimesh = tri.Triangulation(r, z, conn) plt.tricontourf(trimesh, gb_L_inf[0, :]) plt.axis('scaled') plt.colorbar() plt.savefig(datapath + '/' + name + '_tri_rgb.png') plt.close() # np.save(name+'.npy', rel_L_inf) # np.save(name+'_data.npy', x_) # np.save(name+'_rct.npy', x) print("{}, shape = {}: L-inf error = {} at {}".format( name, x.shape, np.max(gb_L_inf), index))
def post(X, Y, DTDN, TEMP, Px, Py, PhiP, dPhidPX, dPhidPY): X = X.reshape(len(X)) Y = Y.reshape(len(X)) TEMP = TEMP.reshape(len(X)) Xdat = np.append(X, Px) Ydat = np.append(Y, Py) Zdat = np.append(TEMP, PhiP) dx = np.append(DTDN[0], dPhidPX) dy = np.append(DTDN[1], dPhidPY) X = np.append(X, X[0]) Y = np.append(Y, Y[0]) levels = np.arange(Zdat.min() - 0.15, Zdat.max() + 0.15, 0.1) plt.figure() plt.plot(X, Y) # plt.tricontourf(Xdat,Ydat,Zdat,11,cmap='jet') plt.tricontourf(Xdat, Ydat, Zdat, levels, cmap='jet') plt.colorbar() plt.axis('equal') # plt.quiver(X,Y,dx,dy) # Xi, Yi, Zi1 = grid(Xdat, Ydat, dx) # Xi, Yi, Zi2 = grid(Xdat, Ydat, dy) # plt.streamplot(Xi,Yi,Zi1,Zi2) return
def plot(grid, solution, filename=None, savefig=True): triang = _setup_triangles(grid) # Interpolate to Refined Triangular Grid interp_lin = tri.LinearTriInterpolator(triang, solution) refiner = tri.UniformTriRefiner(triang) tri_refi, sol_refi = refiner.refine_field(solution, triinterpolator=interp_lin, subdiv=3) # Setup colorbar inf = np.min(sol_refi) sup = np.max(sol_refi) # Plot and save to file plt.figure() plt.triplot(triang) if inf != sup: plt.tricontourf(tri_refi, sol_refi, levels=np.linspace(inf, sup, 11)) else: plt.tricontourf(tri_refi, sol_refi) plt.colorbar() if savefig: plt.savefig(filename) plt.clf() plt.close()
def draw_pdf_contours(dist, border=False, nlevels=200, subdiv=8, **kwargs): '''Draws pdf contours over an equilateral triangle (2-simplex). Arguments: `dist`: A distribution instance with a `pdf` method. `border` (bool): If True, the simplex border is drawn. `nlevels` (int): Number of contours to draw. `subdiv` (int): Number of recursive mesh subdivisions to create. kwargs: Keyword args passed on to `plt.triplot`. ''' from matplotlib import ticker, cm refiner = mtri.UniformTriRefiner(_triangle) trimesh = refiner.refine_triangulation(subdiv=subdiv) pvals = [dist.pdf(xy2bc(xy)) for xy in zip(trimesh.x, trimesh.y)] plt.tricontourf(trimesh, pvals, nlevels, **kwargs) plt.axis('equal') plt.xlim(0, 1) plt.ylim(0, 0.75**0.5) plt.axis('off') if border is True: plt.hold(1) plt.triplot(_triangle, linewidth=1)
def trisurf(p, t, value=None): import numpy as np if p.shape[0] < p.shape[1]: p = np.transpose(p) if t.shape[0] < t.shape[1]: t = np.transpose(t) import matplotlib.pyplot as plt fig, grid = plt.subplots() X = [p[t[:, 0], 0], p[t[:, 1], 0], p[t[:, 2], 0], p[t[:, 0], 0]] Y = [p[t[:, 0], 1], p[t[:, 1], 1], p[t[:, 2], 1], p[t[:, 0], 1]] grid.plot(X, Y, 'k-', linewidth=0.2) if value is not None: if len(value.shape) == 1: value = value.reshape(len(value), 1) name_color_map = 'jet' x = p[:, 0] y = p[:, 1] z = value[:, 0] plt.tricontourf(x, y, t, z, 1000, cmap=name_color_map) plt.colorbar() plt.show()
def hyper_results_3d(data, metric='acc', path=""): fig, ax = plt.subplots(figsize=(9, 9), tight_layout=True) norms, scales = data['norm'][data['score'] < 200], data['scale'][ data['score'] < 200] color_data = data[metric][ data['score'] < 200] if metric == 'score' else data[metric] CS = plt.tricontourf(norms, scales, color_data, cmap=cc.cm.bmy, levels=np.arange(0, 100, 5)) # plt.clabel(CS, inline=1, fontsize=10) plt.show()
def plot_colormap(self, freq=1000, total_pres=True, dinrange=20): """Plots a color map of the pressure field. Parameters ---------- freq : float desired frequency of the color map. If the frequency does not exist on the simulation, then it will choose the frequency just before the target. total_pres : bool Whether to plot the total sound pressure (Default = True) or the reflected only. In the later case, we subtract the incident field Green's function from the total sound field. dinrange : float Dinamic range of the color map Returns --------- plt : Figure object """ id_f = np.where(self.controls.freq <= freq) id_f = id_f[0][-1] # color parameter if total_pres: color_par = 20 * np.log10( np.abs(self.pres_s[0][:, id_f]) / np.amax(np.abs(self.pres_s[0][:, id_f]))) else: r1 = np.linalg.norm(self.sources.coord - self.receivers.coord, axis=1) color_par = np.abs(self.pres_s[0][:,id_f]-\ np.exp(-1j * self.controls.k0[id_f] * r1) / r1) color_par = 20 * np.log10(color_par / np.amax(color_par)) # Create triangulazition triang = tri.Triangulation(self.receivers.coord[:, 0], self.receivers.coord[:, 2]) # Figure fig = plt.figure() #figsize=(8, 8) # fig = plt.figure() fig.canvas.set_window_title('pressure color map') plt.title('Reference |P(f)| (BEM sim)') # p = plt.tricontourf(triang, color_par, np.linspace(-15, 0, 15), cmap = 'seismic') p = plt.tricontourf(triang, color_par, np.linspace(-dinrange, 0, int(dinrange)), cmap='seismic') fig.colorbar(p) plt.xlabel(r'$x$ [m]') plt.ylabel(r'$z$ [m]') return plt
def plot_situation(m, data, proj=None, modeled=None, view_R=2.0, filename=None, min_elevation=None, max_elevation=None, latlon_step=0.5, figsize=(13, 13)): fault_pts = m.get_tri_pts('fault').reshape((-1, 3)) fC = np.mean(fault_pts, axis=0) R = np.sqrt(np.max(np.sum((fault_pts - fC)**2, axis=1))) surf_pts = m.get_tri_pts('surf') if min_elevation is None: min_elevation = int(np.floor(np.min(surf_pts[:, :, 2]) / 1000.0)) if max_elevation is None: max_elevation = int(np.ceil(np.max(surf_pts[:, :, 2]) / 1000.0)) n_steps = (max_elevation - min_elevation) * 2 + 1 levels = np.linspace(min_elevation, max_elevation, n_steps) plt.figure(figsize=figsize) cntf = plt.tricontourf(m.pts[:, 0], m.pts[:, 1], m.get_tris('surf'), m.pts[:, 2] / 1000.0, levels=levels, extend='both') plot_fault_trace(m) plt.triplot(m.pts[:, 0], m.pts[:, 1], m.get_tris('fault'), 'w-', linewidth=0.4) plt.quiver(data['X'], data['Y'], data['EW'], data['SN'], color='r') if modeled is not None: plt.quiver(data['X'], data['Y'], modeled[:, 0], modeled[:, 1], color='w') cbar = plt.colorbar(cntf) cbar.set_label('elevation (km)') map_axis(fC, R, view_R, proj, latlon_step) if filename is not None: plt.savefig(filename) plt.show()
def _computeFilledContoursForLevel(self,levels,extend,polygons,oneLevelOnly=False): data=self.getData() if not data: return x, y, z = data usegrid=self._dataGridShape is not None and self.uUseGrid.isChecked() if usegrid: gx = x.reshape(self._dataGridShape) gy = y.reshape(self._dataGridShape) gz = z.reshape(self._dataGridShape) try: cs = plt.contourf(gx, gy, gz, levels, extend=extend) except: raise ContourGenerationError() elif self._isMPLOk()==True: # If so, we can use the tricontour fonction try: cs = plt.tricontourf(x, y, z, levels, extend=extend) except ValueError as ve: raise ContourGenerationError( ve.message) else: raise ContourGenerationError() levels = [float(l) for l in cs.levels] if extend=='min' or extend==BOTH: levels = np.append([-np.inf,], levels) if extend=='max' or extend==BOTH: levels = np.append(levels, [np.inf,]) # self.progressBar.setRange(0, len(cs.collections)) for i, polygon in enumerate(cs.collections): mpoly = [] for path in polygon.get_paths(): path.should_simplify = False poly = path.to_polygons() exterior = [] holes = [] if len(poly)>0: exterior = poly[0] #and interiors (holes) are in poly[1:] #Crazy correction of one vertice polygon, mpl doesn't care about it if len(exterior) < 2: continue p0 = exterior[0] if len(poly)>1: #There's some holes for h in poly[1:]: if len(h)>2: holes.append(h) mpoly.append([exterior, holes]) if len(mpoly) > 0: polygons.append([i, levels[i], levels[i+1], mpoly]) if oneLevelOnly: break
def fcontour_plot_dataset(file_path, hdf_file_name, x_variable, y_variable, z_variable, clims=None, num_levels=41): '''Script to make a contour plot of a dataset from an HDF5 files of several scans combined. ''' #Create a new figure plt.figure() plt.suptitle(hdf_file_name) #Open file hdf_file = h5py.File(file_path + hdf_file_name, 'r') #Mask off any NAN entries is x; indicates scan wasn't as wide as widest scan mask = np.isfinite(hdf_file[x_variable]) #Make triangulation for Delauney triangulation plot triang = tri.Triangulation(hdf_file[x_variable][mask], hdf_file[y_variable][mask]) #Create contour plot if clims: contour_levels = np.linspace(clims[0], clims[1], num_levels) plt.tricontourf(triang, hdf_file[z_variable][mask], contour_levels, extend='both') else: plt.tricontourf(triang, hdf_file[z_variable][mask], num_levels, extend='both') plt.xlabel(x_variable) plt.ylabel(y_variable) cb = plt.colorbar() cb.ax.set_ylabel(z_variable) plt.show()
def plot_structure(triangles,electrode,materials,solution,grid=True,linewidth=5,mesh=False,elec=True,color='0.7',xlabel='x',ylabel='y',title=True): Y = triangles.y X = triangles.x T = triangles.triangles plt.ylim([max(Y),min(Y)]) unit = '($\mu m$)' plt.xlabel(xlabel + unit) plt.ylabel(ylabel + unit) color_material = ['orange', 'green', 'red', 'purple', 'brown', 'pink', 'gray', 'olive', 'cyan','magenta', 'yellow'] ones = np.ones(len(X)) for i in range(len(materials)): m = materials[i] triangles.set_mask(mask(m,solution,triangles)) plt.tricontourf(triangles,ones,colors=color_material[i]) cmap = colors.ListedColormap(['blue']+color_material[:len(materials)]) norm = plt.Normalize(-2,2*len(materials)) cbar = plt.colorbar(cm.ScalarMappable(norm=norm,cmap=cmap),ticks=range(-1,2*len(materials),2)) cbar.set_ticklabels(['Contact']+materials) if(elec): for e in electrode: b = e[1] x,y = X[b],Y[b] plt.hlines(y[0],x[0],x[1],linewidth=linewidth,colors='blue') if(mesh): plt.triplot(triangles,color=color) plt.title("Mesh") plt.xlim([min(X),max(X)]) if(mesh==False): plt.grid(grid,'both') plt.gca().set_aspect('equal') plt.show()
def plot_u_exact(self, pp=None): if self.dim == 2: if self.is_DiscontinuousGalerkin: ud_aux = np.zeros(self.nV) for i, E in enumerate(self.elements): for ii, Vdx in enumerate(E): ud_aux[Vdx] = self.u_exact[3 * i + ii] plt.tricontourf(self.vertices[:, 0], self.vertices[:, 1], self.elements, ud_aux) plt.triplot(self.vertices[:, 0], self.vertices[:, 1], self.elements, lw=.1, color='white', alpha=.3) #plt.scatter(self.vertices[self.omega, 0], self.vertices[self.omega, 1], c = "black", s=.2, alpha=.7) if pp is None: plt.show() else: plt.savefig(pp, format='pdf') plt.close() else: plt.tricontourf(self.vertices[:, 0], self.vertices[:, 1], self.elements, self.u_exact) plt.triplot(self.vertices[:, 0], self.vertices[:, 1], self.elements, lw=.1, color='white', alpha=.3) #plt.scatter(self.vertices[self.omega, 0], self.vertices[self.omega, 1], c = "black", s=.2, alpha=.7) if pp is None: plt.show() else: plt.savefig(pp, format='pdf') plt.close()
def init_img(): global nc, Q, F, tide ZZ[ZZ > Zmax] = Zmax ZZ[ZZ < Zmin] = Zmin levels = numpy.linspace(Zmin, Zmax, 60) F = plt.tricontourf(X, Y, ele, ZZ, vmin=Zmin, vmax=Zmax, cmap=plt.cm.Spectral_r, levels=levels) plt.clim(Zmin, Zmax) plt.xlabel('Easting (meters)', fontsize=30) plt.ylabel('Northing (meters)', fontsize=30) cbar = plt.colorbar(F, ax=ax) #numpy.linspace(Zmin,Zmax,10)) cbar.set_label(r"Current speed [m.s^-1]", size=30) cbar.ax.tick_params(labelsize=25) plt.draw() nc = None Q = None if bnd is not None: plotpatch(bnd) if lim is not None: ax.set_xlim([lim[0], lim[1]]) ax.set_ylim([lim[2], lim[3]]) else: ax.set_xlim([X.min(), X.max()]) ax.set_ylim([Y.min(), Y.max()]) #ax.set_axis_bgcolor('black') # ADD ELEVATION if plot_elev: rect = [0.1, 0.1, 0.3, 0.2] # l,b,w,h ax2 = fig.add_axes(rect) ax2.plot(time, elev, color='b', lw=2) zeros = elev * 0 tide = ax2.plot([time[0], time[0]], [-1, 1], color='k') ax2.set_ylim([-1, 1]) ax2.set_ylabel('elevation [m]', fontsize=30) ax2.xaxis.set_major_locator(DayLocator()) ax2.xaxis.set_major_formatter(DateFormatter('%d ')) ax2.tick_params(labelsize=25)
def min_pressure(global_path,netcdf_file,ax,title,levels,lon1,lon2,lat1,lat2): xx = netcdf_file.variables['x'][:] yy = netcdf_file.variables['y'][:] gridvars = netcdf_file.variables var_element = 'element' elems = gridvars[var_element][:,:]-1 m = Basemap(projection='cyl',llcrnrlat=lat1,urcrnrlat=lat2,llcrnrlon=lon1,urcrnrlon=lon2,resolution='h', epsg = 4269) data1 = netcdf_file.variables['pressure_min'][:] triang = tri.Triangulation(xx,yy, triangles=elems) m.arcgisimage(service='ESRI_Imagery_World_2D', xpixels=600, verbose= False) m.drawcoastlines(color='k') if data1.mask.any(): point_mask_indices = np.where(data1.mask) tri_mask = np.any(np.in1d(elems, point_mask_indices).reshape(-1, 3), axis=1) triang.set_mask(tri_mask) plt.xlim([lon1, lon2]) plt.ylim([lat1, lat2]) plt.tricontourf(triang, data1, levels=levels,alpha=0.75,vmin=8.75, vmax=10.6, aspect='auto',cmap='jet') cb=plt.colorbar(cmap='jet',fraction=0.026,pad=0.04) cb.set_label('Pressure (kPa)',fontsize=12) plt.title(title + '\n') #plt.savefig('max_WL.png',dpi=500, bbox_inches = 'tight', pad_inches = 0.1) #plt.close() return plt.show()
def plot1(): with open("data_plate_thing.txt", 'r') as f: s = f.read().splitlines() non_zero_data = np.array( [split_line(line) for line in s[1:] if split_line(line)[8] != 0]) min_char_interval = non_zero_data[:, 0] max_char_interval = non_zero_data[:, 1] min_plate_interval = non_zero_data[:, 2] max_plate_interval = non_zero_data[:, 3] tempo = non_zero_data[:, 4] acertos = non_zero_data[:, 8] # Definição dos objetos de triangulação para plotagem triang = tri.Triangulation(min_char_interval, max_char_interval) # Plot 1 - Curvas de nível plt.subplot(1, 2, 1) plt.tricontourf(triang, acertos, levels=np.linspace(np.min(acertos), np.max(acertos), 30)) plt.colorbar() plt.tricontour(triang, acertos, colors='k')
def plotDiversityMesh(self, fignum=1, subplot=1, nsubplots=1, color="k", label=None): plt.figure(fignum) square = int(np.ceil(np.sqrt(nsubplots))) plt.subplot(square, square, subplot) flatDist = self.internalDists.flatten() flatEns = self.normedEns.flatten() ttime = np.zeros_like(self.internalDists) for i in range(self.niters): ttime[i] = i + 1 flatTime = ttime.flatten() plt.tricontourf(flatDist, flatEns, flatTime) plt.title("Diversity and Energy over time") plt.xlabel("Internal Distance") plt.ylabel("Sample Energy") plt.xlim(0, 1) plt.ylim(0, 1) plt.clim(1, self.niters) plt.colorbar() plt.tight_layout()
def make_scan_plots(log_data, grid=False, contour=True): fig = plt.figure() if grid: pts = np.array(list(log_data.cartesians.keys())) plt.plot(pts[:, 0], pts[:, 1], 'o') # plt.close() if contour: pts = log_data.energies mid_oh = (pts[:, 0] / 2) - pts[:, 1] mid_oh *= -1 pot = pts[:, 2] # load rigid data for difference plots rscans = list( sorted(glob.glob(os.path.join(scan_dir, "2Dtet_ri*.log")))) rel = LogInterpreter(*rscans, method='rigid', scancoord_1=(0, 1), scancoord_2=(1, 2), optimized=False) rpts = rel.energies rpot = rpts[:, 2] pot = np.abs((pot - rpot)) pot *= hartowave pot[pot > 2000] = 2000 # pot *= hartowave # pot[pot > 15000] = 15000 plt.tick_params(labelsize=22) plt.rcParams.update({'font.size': 22}) plt.tricontourf(pts[:, 0], mid_oh, pot, cmap='Purples_r', levels=15) plt.ylim(-0.7, 0.2) plt.xlim(2, 4) plt.colorbar() plt.tricontour(pts[:, 0], mid_oh, pot, colors='k', levels=15) # plt.close() return fig
def main(): import numpy as np import matplotlib.pyplot as plt import matplotlib.tri as tri # Load data from CSV data = np.genfromtxt("scan_data.csv", delimiter=',', skip_header=1) T = data[:, 0] h = data[:, 1] m = data[:, 2] triang = tri.Triangulation(T, h) plt.tricontourf(T, h, m, 20, linewidth=0.5, extend='both') plt.axis("tight") plt.colorbar() plt.xlabel('Temperature (T)') plt.ylabel('External Field (h)') plt.title('Magnetization') plt.savefig('test.pdf') plt.show() return 0
def plot_tricontour(self): # tricontour. x = self._x y = self._y z = self._z n_labels = self._n_labels zi = self._zi x_min = self._x_min y_min = self._y_min x_max = self._x_max y_max = self._y_max title = self._title x_label = self._x_label y_label = self._y_label ax = plt.subplot(111) # change this if you want to plot both triang = tri.Triangulation(x, y) plt.tricontour(x, y, z, n_labels, linewidths=0.5, colors='k') plt.tricontourf(x, y, z, n_labels, cmap=plt.cm.rainbow, norm=plt.normalize(vmax=abs(zi).max(), vmin=-abs(zi).max())) labels = ax.get_xticklabels() for label in labels: label.set_rotation(30) plt.colorbar() plt.plot(x, y, 'ko', ms=3) plt.xlim(x_min, x_max) plt.ylim(y_min, y_max) plt.xlabel(x_label) plt.ylabel(y_label) plt.title(title) print('tricontour plotted')
def plotMapAtTime(ncfilepath, timeIndex): ds = Dataset(ncfilepath) hs = ds.variables['hs'][timeIndex, :] #hs = ds.variables['vwnd'][timeIndex, :] xs = ds.variables['longitude'][:] ys = ds.variables['latitude'][:] hs[hs.mask] = 0 levels = np.arange(0., np.max(hs.flatten())*1.05, .02) cf = plt.tricontourf(xs, ys, hs, levels) #cf = bm.contourf(xs, ys, hs, tri=True) cf.cmap.set_over([.5,0,0]) #cf.set_clim(0, 1.6) plt.colorbar() #plt.savefig('plt_t=' + str(timeIndex) + '.png') plt.show()
def plot(self, func, dir_, itr, time, xlabel = 'x', ylabel = 'y', quantity = '', show = False): if dir_[-1] != '/': dir_ = dir_ + '/' self.dir = dir_ self.func = np.vectorize(func) # func must be vectorized plt.clf() plt.xlabel(xlabel) plt.ylabel(ylabel) self.quantity = quantity p = plt.tricontourf(self.x, self.y, self.mesh.cells(), self.func(self.x, self.y), 20) plt.colorbar(p) plt.legend([quantity, 'time = {:.4f}'.format(time)]) if show is True: plt.show() plt.savefig(self.dir + self.quantity + '_' + self.id + '_' + '{:04.0f}'.format(itr)) print('Plot #{} generated'.format(itr), end = '\r')
def vectorize(lat, lon, elems, data, res, prev, thres): print("Distributing levels...") MinVal = np.min(data) MaxVal = np.max(data) levels = np.linspace(MinVal, MaxVal, num=str(int(res) + 1)) print("Contouring data...") triangles = tri.Triangulation(lon, lat, triangles=elems) contour = plt.tricontourf(triangles, data, levels=levels, extend='max') # preview and confirm if (prev): plt.show() if not prompt("Would you like to write this data?"): exit() return genPoly(contour, levels, thres)
def plot_contourf(self, num_levels=50, **kwargs): """Filled contour plot of the xy plane Parameters ---------- num_levels : int Number of contour levels. **kwargs Forwarded to :func:`~matplotlib.pyplot.tricontourf`. """ levels = np.linspace(self.data.min(), self.data.max(), num=num_levels) x, y, _ = self.positions kwargs = with_defaults(kwargs, levels=levels, rasterized=True) contourf = plt.tricontourf(x, y, self.data, **kwargs) self._decorate_plot() return contourf
def showresults(self): X, Y = np.meshgrid(np.arange(-1, 1 + .1, .1), np.arange(-1, 1 + .1, .1)) xx = np.reshape(X, [-1]) yy = np.reshape(Y, [-1]) xy = np.vstack([xx, yy]).T triang = tri.Triangulation(self.params[:, 0], self.params[:, 1]) zz = self.anninst.var(self.params) cf = plt.tricontourf(self.params[:, 0], self.params[:, 1], zz) plt.scatter(self.x[:, 0], self.x[:, 1], s=49, c='w') plt.scatter(self.x[:, 0], self.x[:, 1], s=16, c='k') plt.triplot(triang, lw=0.5, color='white') plt.colorbar(cf) plt.show()
def raw_plot_tricontourf(x_coord, y_coord, plot_data, ax = None, levels = 20): """ plots the raw data with tricontourf Returns: ax, mesh for editing/formatting purposes """ if ax is None: ax = plt.axes(projection = proj) mesh = plt.tricontourf(x_coord.flatten(), y_coord.flatten(), plot_data.flatten(), levels) # magic command to get rid of white lines in contourf outputs for c in mesh.collections: c.set_edgecolor("face") return (ax, mesh)
def plotSoln(self, plt, solVec, title=""): plt.set_title(title) # plt.set_xlabel('x',size=14,weight='bold') # plt.set_ylabel('y',size=14,weight='bold') plt.set_aspect('equal') plt.set_xlim(-0.1, 5.1) plt.set_ylim(-0.1, 1.2) xy = np.asarray(self.mesh.vertices) if xy.size < 10000: plt.triplot(xy[:, 0], xy[:, 1], self.mesh.elements, 'b-', linewidth=0.5) vals = plt.tricontourf(self.mesh.dtri, solVec, cmap="jet") return vals
def tricontourf(self, *args, axes=None, **kwargs): if np.any(self.values.mask): self.triangulation.set_mask( np.any(self.values.mask[self.triangulation.triangles], axis=1)) _ax = plt.tricontourf( self.triangulation, self.values, cmap=kwargs.get('cmap', self._cmap), levels=kwargs.get('levels', self._levels), vmin=kwargs.get('vmin', np.min(self.values)), vmax=kwargs.get('vmax', np.max(self.values)), ) self.triangulation.set_mask(None) if kwargs.get('cbar') is not None: plt.colorbar(_ax) plt.gca().axis('scaled') return axes
def test_tricontourf_decreasing_levels(): # github issue 5477. x = [0.0, 1.0, 1.0] y = [0.0, 0.0, 1.0] z = [0.2, 0.4, 0.6] plt.figure() with pytest.raises(ValueError): plt.tricontourf(x, y, z, [1.0, 0.0])