def make_scan_plots(self, grid=False, contour=True): plt.rcParams.update({'font.size': 20}) fig = plt.figure(dpi=600) if grid: pts = np.array(list(self.logData.cartesians.keys())) plt.plot(pts[:, 0], pts[:, 1], 'ok', markersize=1.5) # plt.close() if contour: pts = self.logData.rawenergies pot = pts[:, 2] potwv = Constants.convert(pot, "wavenumbers", to_AU=False) potwv[potwv > 24000] = 24000 plt.tricontourf(pts[:, 0], pts[:, 1], potwv, cmap='viridis', levels=8) cb = plt.colorbar() cb.set_label("Energy ($\mathrm{cm^{-1}}$)") plt.tricontour(pts[:, 0], pts[:, 1], potwv, colors='k', levels=8) plt.xlabel("$\mathrm{R_{OO}}$ ($\mathrm{\AA}$)") plt.ylabel("$\mathrm{r_{XH}}$ ($\mathrm{\AA}$)") # plt.axis("off") plt.savefig( f"{self.fig_dir}/{self.molecule.MoleculeName}_XH_OOpot.png", dpi=fig.dpi, bbox_inches="tight")
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 plot_surfaces(data, show_samples=False, path=""): alpha_x = data[:, 0] alpha_y = data[:, 1] losses = data[:, 2] accs = data[:, 3] fig, ax = plt.subplots(figsize=(12, 9)) if show_samples: plt.plot(alpha_x, alpha_y, 'ko', color='black', ms=2) # plt.tricontourf(alpha_x, alpha_y, losses, cmap='viridis', levels=np.arange(0.1, 100, 0.5)) CS = plt.tricontour(alpha_x, alpha_y, losses, cmap='viridis', levels=np.arange(0.1, 10, 0.5)) plt.clabel(CS, inline=1, fontsize=8) plt.xlim(-1, 1) plt.ylim(-1, 1) plt.tick_params(labelsize=12) plt.tight_layout() plt.savefig(path + "_loss_landscape.pdf" if path else "loss_landscape.pdf", format='pdf', dpi=1200) fig, ax = plt.subplots(figsize=(12, 9)) if show_samples: plt.plot(alpha_x, alpha_y, 'ko', color='black', ms=2) # plt.tricontourf(alpha_x, alpha_y, accs, cmap='plasma', levels=np.arange(0.01, 1, 0.05)) CS = plt.tricontour(alpha_x, alpha_y, accs, cmap='plasma', levels=np.arange(1, 100, 5)) plt.clabel(CS, inline=1, fontsize=8) plt.xlim(-1, 1) plt.ylim(-1, 1) plt.tick_params(labelsize=12) plt.tight_layout() plt.savefig(path + "_accuracy_landscape.pdf" if path else "accuracy_landscape.pdf", format='pdf', dpi=1200)
def plot_frame(df, datforfig, frame): """Generates the figure""" xyzdat, fitraveled, diff = datforfig extx = (np.min(xyzdat[0]), np.max(xyzdat[0]), np.min(xyzdat[1]), np.max(xyzdat[1])) fig = plt.figure(figsize=(8,3)) plt.subplot(1, 2, 1) contour_plot(df) plt.tricontour(xyzdat[0], xyzdat[1], fitraveled, 5, extent=extx, linewidths=1, colors='k') plt.title('Fit') x1d, y1d, z2draw = df_separate(df) z2d = np.reshape(diff, (len(y1d), len(x1d))) diffdf = df_join(x1d, y1d, z2d.transpose()) plt.subplot(1, 2, 2) contour_plot(diffdf) plt.title('Difference') plt.subplots_adjust(top=0.8, bottom=0.196, left=0.138, right=0.898, hspace=0.2, wspace=0.55) fig.patch.set_facecolor('w') plt.suptitle(str(frame), verticalalignment = 'top') plt.show() return fig
def test_tri_smooth_gradient(): # Image comparison based on example trigradient_demo. def dipole_potential(x, y): """ An electric dipole potential V """ r_sq = x**2 + y**2 theta = np.arctan2(y, x) z = np.cos(theta) / r_sq return (np.max(z) - z) / (np.max(z) - np.min(z)) # Creating a Triangulation n_angles = 30 n_radii = 10 min_radius = 0.2 radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 2 * 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)).flatten() y = (radii * np.sin(angles)).flatten() V = dipole_potential(x, y) triang = mtri.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) # Refine data - interpolates the electrical potential V refiner = mtri.UniformTriRefiner(triang) tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3) # Computes the electrical field (Ex, Ey) as gradient of -V tci = mtri.CubicTriInterpolator(triang, -V) (Ex, Ey) = tci.gradient(triang.x, triang.y) E_norm = np.sqrt(Ex**2 + Ey**2) # Plot the triangulation, the potential iso-contours and the vector field plt.figure() plt.gca().set_aspect('equal') plt.triplot(triang, color='0.8') levels = np.arange(0., 1., 0.01) cmap = cm.get_cmap(name='hot', lut=None) plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap, linewidths=[2.0, 1.0, 1.0, 1.0]) # Plots direction of the electrical vector field plt.quiver(triang.x, triang.y, Ex / E_norm, Ey / E_norm, units='xy', scale=10., zorder=3, color='blue', width=0.007, headwidth=3., headlength=4.)
def draw_nodal_values_contour(values, coords, edof, levels=12, title=None, dofs_per_node=None, el_type=None, draw_elements=False): """Draws element nodal values as filled contours. Element topologies supported are triangles, 4-node quads and 8-node quads.""" edof_tri = topo_to_tri(edof) ax = plt.gca() ax.set_aspect('equal') x, y = coords.T v = np.asarray(values) plt.tricontour(x, y, edof_tri - 1, v.ravel(), levels) if draw_elements: if dofs_per_node != None and el_type != None: draw_mesh(coords, edof, dofs_per_node, el_type, color=(0.2, 0.2, 0.2)) else: info( "dofs_per_node and el_type must be specified to draw the mesh." ) if title != None: ax.set(title=title)
def plot_patch(mesh_container, x, d, vmin=0, vmax=1, contours=True): px = zkronv(tt.xfun(2, d), tt.ones(2, d)) py = zkronv(tt.ones(2, d), tt.xfun(2, d)) px = px.full().flatten('F').astype(np.int) py = py.full().flatten('F').astype(np.int) pts = np.array([mesh_container._pts(ex, ey) for ex, ey in zip(px, py)]) tri = Delaunay(pts) plt.tripcolor(pts[:, 0], pts[:, 1], tri.simplices.copy(), x, shading='gouraud', vmin=vmin, vmax=vmax) if contours: plt.tricontour(pts[:, 0], pts[:, 1], tri.simplices.copy(), x, np.linspace(vmin, vmax, 11), colors='k') d = mesh_container.d p1 = mesh_container._pts(0, 0) p2 = mesh_container._pts(2**d - 1, 0) p3 = mesh_container._pts(2**d - 1, 2**d - 1) p4 = mesh_container._pts(0, 2**d - 1) plt.plot([p1[0], p2[0], p3[0], p4[0]], [p1[1], p2[1], p3[1], p4[1]], 'm')
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 plot2(): 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_plate_interval, max_plate_interval) # Plot 1 - Curvas de nível plt.subplot(1, 2, 2) # plt.gca().set_aspect('equal') plt.tricontourf(triang, acertos, levels=np.linspace(np.min(acertos), np.max(acertos), 30)) plt.colorbar() plt.tricontour(triang, acertos, colors='k')
def drawplot(filein, fileout, model, offtot=0, offBs=0, offRK=0): ''' Draw the plot using shaded areas for the global fit and contour lines for Bs-only and RK-only fits ''' fig = texfig.figure() trgtot, ztot = triang(readfile(filein, -1, 9, offtot)) plt.tricontourf(trgtot, ztot, levels=[0.0, 1.0, 4.0, 9.0], colors=('#00B400', '#00FF00', '#BFFF80')) trgBs, zBs = triang(readfile(filein, -2, 6, offBs)) plt.tricontour(trgBs, zBs, levels=[1.0, 4.0], colors='b', linestyles=('-', '--')) trgRK, zRK = triang(readfile(filein, -3, 6, offRK)) plt.tricontour(trgRK, zRK, levels=[1.0, 4.0], colors='#800000', linestyles=('-.', ':')) if model == 'LQ': plt.xlabel(r"$M_{S_3} [\mathrm{TeV}]$") plt.ylabel(r'$\mathrm{Im}\ y^{QL}_{32}y^{QL*}_{32}$') if model == 'Z': plt.xlabel(r"$M_{Z'} [\mathrm{TeV}]$") plt.ylabel(r'$\mathrm{Im}\ \lambda^Q_{23}$') texfig.savefig(fileout)
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_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 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())) 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 test_tri_smooth_gradient(): # Image comparison based on example trigradient_demo. def dipole_potential(x, y): """ An electric dipole potential V """ r_sq = x ** 2 + y ** 2 theta = np.arctan2(y, x) z = np.cos(theta) / r_sq return (np.max(z) - z) / (np.max(z) - np.min(z)) # Creating a Triangulation n_angles = 30 n_radii = 10 min_radius = 0.2 radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 2 * 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)).flatten() y = (radii * np.sin(angles)).flatten() V = dipole_potential(x, y) triang = mtri.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) # Refine data - interpolates the electrical potential V refiner = mtri.UniformTriRefiner(triang) tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3) # Computes the electrical field (Ex, Ey) as gradient of -V tci = mtri.CubicTriInterpolator(triang, -V) (Ex, Ey) = tci.gradient(triang.x, triang.y) E_norm = np.sqrt(Ex ** 2 + Ey ** 2) # Plot the triangulation, the potential iso-contours and the vector field plt.figure() plt.gca().set_aspect("equal") plt.triplot(triang, color="0.8") levels = np.arange(0.0, 1.0, 0.01) cmap = cm.get_cmap(name="hot", lut=None) plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap, linewidths=[2.0, 1.0, 1.0, 1.0]) # Plots direction of the electrical vector field plt.quiver( triang.x, triang.y, Ex / E_norm, Ey / E_norm, units="xy", scale=10.0, zorder=3, color="blue", width=0.007, headwidth=3.0, headlength=4.0, )
def genPredPlot(X, Y): plt.style.use('bmh') feature1, feature2 = X[:, 1], X[:, 2] feature1Neg = [ feature1.item(i) for i in range(Y.shape[1]) if Y.item(i) == 0 ] feature1Pos = [ feature1.item(i) for i in range(Y.shape[1]) if Y.item(i) == 1 ] feature2Neg = [ feature2.item(i) for i in range(Y.shape[1]) if Y.item(i) == 0 ] feature2Pos = [ feature2.item(i) for i in range(Y.shape[1]) if Y.item(i) == 1 ] # plot scatters of original data plt.subplot(2, 1, 1) negPlot, = plt.plot(feature1Neg, feature2Neg, 'bo') posPlot, = plt.plot(feature1Pos, feature2Pos, 'ro') xAxis = np.linspace(np.min(feature1) - 1, np.max(feature1) + 1, num=11) # generate samples of theta sampleSize = 8000 thetas = generateSamplesMat( [theta_opt.item(i) for i in range(theta_opt.shape[0])], np.linalg.inv(hessian_opt), sampleSize) # plot predicted boundary XPredMat = 7 * np.random.rand(10000, 2) - 3 X_bias = np.hstack((np.ones((XPredMat.shape[0], 1)), XPredMat)).transpose() yPred = predict(X_bias, np.matrix(thetas)) n_levels = 20 levels = np.linspace(1.1 * np.min(yPred), 1.1 * np.max(yPred), n_levels) plt.tricontour(X_bias[1, :], X_bias[2, :], [yPred.item(i) for i in range(yPred.shape[1])], levels=levels) plt.axis([ 1.1 * np.min(feature1), 1.1 * np.max(feature1), 1.1 * np.min(feature2), 1.1 * np.max(feature2) ]) plt.xlabel('hours studied') plt.ylabel('grade in class') plt.legend((negPlot, posPlot), ('failed', 'passed'), loc=3) plt.title('Posterior Predictive Distribution') plt.subplot(2, 1, 2) value = sigmoid(theta_opt.transpose() * X_bias) - yPred plt.hist([value.item(i) for i in range(value.shape[1])], bins=100) plt.title('Histogram of Prediction Difference in MCMC and MAP') plt.savefig('p3.pdf', format='pdf') plt.tight_layout() plt.show()
def _add_SSE_contour(x, y, color, label, columns, SSE, compare): ax = plt.gca() xvar, yvar, loc = _get_variables(ax, columns) x = SSE[xvar] y = SSE[yvar] z = SSE['SSE'] triang = tri.Triangulation(x, y) plt.tricontour(triang, z, [compare], colors='r')
def _add_LR_contour(x,y,color,label,columns,data,theta_star,threshold): ax = plt.gca() xvar, yvar, loc = _get_variables(ax,columns) X, Y, Z = _get_data_slice(xvar,yvar,columns,data,theta_star) triang = tri.Triangulation(X, Y) plt.tricontour(triang,Z,[threshold], colors='r')
def main(): loaded_matrix = unpickle_elevation_matrix("matrix_pickle_k2.bin") x, y, z = convert_matrix(loaded_matrix, 300) plot_mlab(x, y, z) plt.tricontour(x.ravel(), y.ravel(), z.ravel(), 100) plt.show() print("stop")
def _add_LR_contour(x, y, color, label, columns, data, theta_star, threshold): ax = plt.gca() xvar, yvar, loc = _get_variables(ax, columns) X, Y, Z = _get_data_slice(xvar, yvar, columns, data, theta_star) triang = tri.Triangulation(X, Y) plt.tricontour(triang, Z, [threshold], colors='r')
def plot_surf_disp(m, side, field, name, vmin=None, vmax=None, filename=None, view_R=1.0, proj=None, latlon_step=0.5): fC, R = get_fault_centered_view(m) if vmin is None: vmin = np.min(field) if vmax is None: vmax = np.max(field) cmap = 'PuOr_r' levels = np.linspace(vmin, vmax, 17) plt.figure(figsize=(10, 10)) fault_start_idx = m.get_start('fault') for i in range(2): which_tris = np.where( np.logical_or(side[:fault_start_idx] == 0, side[:fault_start_idx] == i + 1))[0] reduced_m = mesh_fncs.remove_unused_pts((m.pts, m.tris[which_tris])) soln_vals = np.empty(reduced_m[0].shape[0]) soln_vals[reduced_m[1]] = field[which_tris] triang = tri.Triangulation(reduced_m[0][:, 0], reduced_m[0][:, 1], triangles=reduced_m[1]) tri_refi, interp_vals = triang, soln_vals cntf = plt.tricontourf(tri_refi, interp_vals, cmap=cmap, levels=levels, extend='both') plt.tricontour(tri_refi, interp_vals, levels=levels, colors='#333333', linestyles='solid', linewidths=0.75) plot_fault_trace(m) cbar = plt.colorbar(cntf) cbar.set_label('$\\text{displacement (m)}$') map_axis(fC, R, view_R, proj, latlon_step) plt.title(name) if filename is not None: plt.savefig(filename) plt.show()
def plot_fnc(triang, f): levels = np.linspace(np.min(f) - 1e-12, np.max(f) + 1e-12, 21) cntf = plt.tricontourf(triang, f, levels=levels, cmap='RdBu') plt.tricontour(triang, f, levels=levels, linestyles='solid', colors='k', linewidths=0.5) plt.colorbar(cntf)
def contour(*arguments, **kwargs): """Call signatures:: contour(X, Y, C, N, **kwargs) contour(X, Y, C, V, **kwargs) Create a contour 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 = 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.tricontour(triang, data, **kwargs) elif arglen == 4: h = plt.tricontour(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 contour(*arguments, **kwargs): """Call signatures:: contour(X, Y, C, N, **kwargs) contour(X, Y, C, V, **kwargs) Create a contour 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 = 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.tricontour(triang, data, **kwargs) elif arglen == 4: h = plt.tricontour(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 CreateFig(dt_output=0.1): from tables import open_file archive = open_file('dambreak.h5','r') import dambreak dambreak.outputStepping.dt_output=dt_output dambreak.outputStepping.nDTout=None dambreak.outputStepping.setOutputStepping() dambreak.myTpFlowProblem.initializeAll() import matplotlib.tri as mtri from matplotlib import pyplot as plt import numpy as np domain = dambreak.domain domain.L = dambreak.tank_dim domain.x = (0.,0.,0.) nodes = archive.get_node("/nodesSpatial_Domain0") x=nodes[:,0] y=nodes[:,1] elements = archive.get_node("/elementsSpatial_Domain0") triang = mtri.Triangulation(x, y, elements) xg = np.linspace(0, domain.L[0], 20) yg = np.linspace(0, domain.L[1], 20) xi, yi = np.meshgrid(xg,yg) plt.figure() for it,t in enumerate(dambreak.myTpFlowProblem.so.tnList[:]): phi = archive.get_node("/phi_t{0:d}".format(it)) vof = archive.get_node("/vof_t{0:d}".format(it)) wvof = np.ones(vof.shape,'d') wvof -= vof u = archive.get_node("/u_t{0:d}".format(it)) v = archive.get_node("/v_t{0:d}".format(it)) plt.clf() plt.xlabel(r'z[m]') plt.ylabel(r'x[m]') colors = ['w','b', 'g','r','c','m','y','k']*(max(domain.segmentFlags)//8 + 1) plt.xlim(domain.x[0]-0.1*domain.L[0],domain.x[0]+domain.L[0]+0.1*domain.L[0]) for si,s in enumerate(domain.segments): plt.plot([domain.vertices[s[0]][0], domain.vertices[s[1]][0]], [domain.vertices[s[0]][1], domain.vertices[s[1]][1]], color=colors[domain.segmentFlags[si]-1], linewidth=2, marker='o') plt.tricontourf(x,y,elements,wvof*np.sqrt(u[:]**2 + v[:]**2)) plt.tricontour(x,y,elements,phi,[0], linewidths=4) u_interp_lin = mtri.LinearTriInterpolator(triang, u[:]) v_interp_lin = mtri.LinearTriInterpolator(triang, v[:]) u_lin = u_interp_lin(xi, yi) v_lin = v_interp_lin(xi, yi) plt.streamplot(xg, yg, u_lin, v_lin,color='k') plt.title('T={0:2.2f}'.format(t)) plt.axis('equal') plt.xlim((0,domain.L[0])) plt.savefig('phi{0:04d}.png'.format(it))
def contour(self, *args, **kwargs): """ Show contours of values.""" fig, ax = plt.subplots(figsize=settings["figsize"]) # Projection circle ax.text(0, 1.02, "N", ha="center", va="baseline", fontsize=16) ax.add_artist(plt.Circle((0, 0), 1, color="w", zorder=0)) ax.add_artist(plt.Circle((0, 0), 1, color="None", ec="k", zorder=3)) ax.set_aspect("equal") plt.tricontour(self.triang, self.values, *args, **kwargs) plt.colorbar() plt.axis('off') plt.show()
def CreateFig(): from tables import openFile archive = openFile('linear_waves.h5','r') import linear_waves import linear_waves_so import matplotlib.tri as mtri from matplotlib import pyplot as plt import numpy as np domain = linear_waves.domain nodes = archive.getNode("/nodesSpatial_Domain0") x=nodes[:,0] y=nodes[:,1] elements = archive.getNode("/elementsSpatial_Domain0") triang = mtri.Triangulation(x, y, elements) domain.L=linear_waves.tank_dim domain.x=[0.,0.] xg = np.linspace(0, domain.L[0], 20) yg = np.linspace(0, domain.L[1], 20) xi, yi = np.meshgrid(xg,yg) plt.figure() for it,t in enumerate(linear_waves_so.tnList[:]): phi = archive.getNode("/phi_t"+`it`) vof = archive.getNode("/vof_t"+`it`) wvof = np.ones(vof.shape,'d') wvof -= vof u = archive.getNode("/u_t"+`it`) v = archive.getNode("/v_t"+`it`) plt.clf() plt.xlabel(r'z[m]') plt.ylabel(r'x[m]') colors = ['b','g','r','c','m','y','k','w'] plt.xlim(domain.x[0]-0.1*domain.L[0],domain.x[0]+domain.L[0]+0.1*domain.L[0]) for si,s in enumerate(domain.segments): plt.plot([domain.vertices[s[0]][0], domain.vertices[s[1]][0]], [domain.vertices[s[0]][1], domain.vertices[s[1]][1]], color=colors[domain.segmentFlags[si]-1], linewidth=2, marker='o') plt.tricontourf(x,y,elements,wvof*np.sqrt(u[:]**2 + v[:]**2)) plt.tricontour(x,y,elements,phi,[0], linewidth=4) u_interp_lin = mtri.LinearTriInterpolator(triang, u[:]) v_interp_lin = mtri.LinearTriInterpolator(triang, v[:]) u_lin = u_interp_lin(xi, yi) v_lin = v_interp_lin(xi, yi) plt.streamplot(xg, yg, u_lin, v_lin,color='k') plt.title('T=%2.2f' % (t,)) plt.xlim((0,domain.L[0])) plt.ylim(0,domain.L[1]) plt.savefig('phi%4.4d.png' % (it,))
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, **k): x = [] y = [] z = [] for n in self.nodes: x.append(n.x) y.append(n.y) z.append(k['r'][n.i-1]) t = tri.Triangulation(x, y) plt.tricontour(t, z, 15, linewidths=0.5) #plt.tricontourf(t, z, 15, cmap=plt.cm.rainbow) plt.colorbar() #plt.plot(x, y, 'ko', ms=3)
def plotcontour(md, par, **kwargs): if hasattr(md.results, 'TransientSolution'): if hasattr(md.results.TransientSolution[-1], 'catch_mesh'): lens = [] for q in range(len(md.results.TransientSolution[-1].catch_mesh)): lens.append( len(md.results.TransientSolution[-1].catch_mesh[q][0])) try: tricontour(md.mesh.x, md.mesh.y, np.squeeze(par), **kwargs) except: right_index = int( np.nonzero(lens == np.intersect1d(lens, len(par)))[0]) tricontour(md.results.TransientSolution[-1].catch_mesh[right_index][0], md.results.TransientSolution[-1].catch_mesh[right_index][1], np.squeeze(par), **kwargs)
def splineContourPlot(self, cmap='twilight_shifted', save=False, axis=False, showLift=False, lvs=40): # Visualizza curve di livello su grafico 2D della superficie B-spline. # showLift: se true mostra i triangoli di sollevamento utilizzati nella costruzione della superficie; # lvs: numero di livelli da mostrare. if not axis: plt.axis('off') plt.axis('equal') # Settaggio dei livelli. (mn, mx) = (min(self.plotHeights), max(self.plotHeights)) tol = 6e-3 if mn < -tol: lvs = int(lvs / 2) levels = np.block( [np.linspace(mn, -tol, lvs), np.linspace(tol, mx, lvs)]) else: levels = np.linspace(tol, mx, lvs) # Visualizzazione delle curve di livello. plt.tricontour(self.plotTriangulation, self.plotHeights, levels=levels, cmap=cmap, linewidths=0.4) # Visualizzazione del dominio e dei triangoli di sollevamento, se richiesti. self.domain.domainPlot(labels=False, legend=False, showExecute=False, color='#000000', colorPS='#000000') if showLift: self.lift_triangles.liftPlot(onlyLifts=True, legend=False, labels=False, showExecute=False) # Salvo l'immagine, se richiesto. if save: name = input('Nome del file?\n') plt.savefig(name, dpi=600) plt.show()
def computeContours(self): extend = self.uExtend.itemText(self.uExtend.currentIndex()) data = self.getData() if not data: return x, y, z = data levels = self.getLevels() if not levels: return try: if self._isMPLOk( ) == True: # If so, we can use the tricontour function try: cs = plt.tricontour(x, y, z, levels, extend=extend) except: raise ContourGenerationError() else: gx = x.reshape(self._nr, self._nc) gy = y.reshape(self._nr, self._nc) gz = z.reshape(self._nr, self._nc) cs = plt.contour(gx, gy, gz, levels, extend=extend) except: raise lines = list() levels = [float(l) for l in cs.levels] for i, line in enumerate(cs.collections): linestrings = [] for path in line.get_paths(): if len(path.vertices) > 1: linestrings.append(path.vertices) lines.append([i, levels[i], linestrings]) self.progressBar.setValue(i + 1) return lines
def chi_sq_contour(analysis_dict): plt.figure() cnorm = mpl.colors.Normalize(vmin=0., vmax=20.) #40.) x = analysis_dict['r_eff'] y = analysis_dict['COT'] z = analysis_dict['difference'] b = plt.tricontour(x, y, z, 70, norm=cnorm) #70) plt.xlabel('Cloud Particle Effective Radius (r_eff) (um)', fontsize=18) plt.ylabel('Cloud Optical Thickness (COT)', fontsize=18) plt.title(analysis_dict['phase'] + ' Cloud {} Wavelength Retrieval Values'.format( str(analysis_dict['num_retrieval_wavelengths'])), fontsize=20) plt.clabel(b, inline=1, fontsize=15) reff_best = analysis_dict['best_reff'] COT_best = analysis_dict['best_COT'] label = 'COT: ' + str(round(COT_best, 2)) + ', r_eff: ' + str(reff_best) + 'um' bbox = dict(boxstyle="round", fc="0.8", alpha=1) arrow = dict(facecolor='black', shrink=0.05) plt.annotate(label,[reff_best,COT_best],xytext=(reff_best+2,COT_best+0.5),\ bbox=bbox,fontsize=15,arrowprops=arrow) plt.scatter(reff_best, COT_best, marker="X", c='k', s=70) return
def along_width(md, par, **kwargs): cont = tricontour(md.mesh.x, md.mesh.y, par, **kwargs) lines = cont.__dict__['allsegs'][0] if len(lines) == 2: upper = np.transpose(lines[0])[:, :len(lines[1])] lower = np.transpose(list(reversed(lines[1])))[:, :len(lines[0])] width = [(np.array(upper[1]) - np.array(lower[1])), upper[0]] else: x_coords = np.transpose(lines)[0] x_coords = x_coords[:int(len(x_coords) / 2)] w = np.transpose(lines)[1] width = [ w[:int(ceil(len(w) / 2))] - w[int(len(w) / 2):len(w)], x_coords ] width[0] = width[0][:len(width[1])] width[1] = width[1][:len(width[0])] return width
def plot_mesh(mesh, dims=2, node_labels=False, vals=None, with_colorbar=False, levels=None, border=None): if not isinstance(mesh.points, np.ndarray): mesh.points = np.array(mesh.points) nodes_x = mesh.points[:, 0] nodes_y = mesh.points[:, 1] if dims == 2: elements_tris = [c for c in mesh.cells if c.type == "triangle"][0].data #plt.figure(figsize=(8, 8)) if vals is None: plt.triplot(nodes_x, nodes_y, elements_tris, alpha=0.9, color='r') else: triangulation = tri.Triangulation(nodes_x, nodes_y, elements_tris) p = plt.tricontourf(triangulation, vals, 30) if with_colorbar: plt.colorbar() if levels: cn = plt.tricontour(triangulation, vals, levels, colors='w') plt.clabel(cn, fmt='%0.2f', colors='k', fontsize=10) if border: plt.hlines(1 - border, -1 + border, 1 - border, 'r') plt.hlines(-1 + border, -1 + border, 1 - border, 'r') plt.vlines(1 - border, -1 + border, 1 - border, 'r') plt.vlines(-1 + border, -1 + border, 1 - border, 'r') if node_labels: for i, (x, y) in enumerate(zip(nodes_x, nodes_y)): plt.text(x, y, i) if vals is not None: return p
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 plotiso_SubTh2simp2D(q, me, u, **kwargs): plane = kwargs.pop('plane', True) niso = kwargs.pop('niso', 15) isorange = kwargs.pop('isorange', None) color = check_color(kwargs.pop('color', None)) cmap = kwargs.pop('cmap', plt.cm.get_cmap(name='viridis')) if isorange is None and niso > 1: isorange = np.linspace(min(u), max(u), num=niso) else: if np.isscalar(isorange): isorange = np.array([isorange]) else: isorange = np.sort(isorange) if color is not None: kwargs['colors'] = np.tile(color, (len(isorange), 1)) else: kwargs['cmap'] = cmap #kwargs['vmin']=kwargs.get('vmin',np.min(u)) #kwargs['vmax']=kwargs.get('vmax',np.max(u)) fig = plt.gcf() if plane: return plt.tricontour( q[:, 0], q[:, 1], me, u, isorange, **kwargs) #vmin=vmin,vmax=vmax, shading=shading,**kwargs) nq = q.shape[0] assert isinstance(u, np.ndarray) and u.shape[0] == nq Q = np.concatenate((q, u.reshape((nq, 1))), axis=1) assert False, "Not yet implemented" return plotiso_SubTh2simp3D(Q, me, u, isorange=isorange, **kwargs)
def update(step_i): t_step = trajectory[step_i] t_x = t_step[:, 0] t_y = t_step[:, 1] t = np.multiply(t_x, t_y) cont = plt.tricontour(nodes_x, nodes_y, t) return cont
def plot_quantity(filename_bin, filename_non, plotnum, qty='vel', limits=[-20, 20]): hdu_v = fits.open(filename_bin) hdu = fits.open(filename_non) data_v = hdu_v[1].data data = hdu[2].data if qty == 'vel': v = data_v['VPXF'] - np.mean(data_v['VPXF']) elif qty == 'sigma': v = data_v['SPXF'] elif qty == 'h3': v = data_v['H3PXF'] else: v = data_v['H4PXF'] plt.subplot(220 + plotnum) img = display_bins_generators(data_v['YS'], data_v['XS'], v, data['D'], data['A'], vmin=limits[0], vmax=limits[1], pixelsize=None) plt.tricontour(data_v['YS'], data_v['XS'], -2.5*np.log10(data_v['FLUX']/np.max(data_v['FLUX'])), levels=np.arange(20), colors='k', linewidths=contourthickness) if plotnum == 1: plt.title("$ \langle V \\rangle $ [km/s]", fontsize=titlesize, y=1.04) plt.ylabel("arcsec", fontsize=textsize) if plotnum == 2: plt.title("$\sigma$ [km/s]", fontsize=titlesize, y=1.04) if plotnum == 3: plt.title("$h_3$", fontsize=titlesize, y=1.04) plt.ylabel("arcsec", fontsize=textsize) plt.xlabel("arcsec", fontsize=textsize) if plotnum == 4: plt.title("$h_4$", fontsize=titlesize, y=1.04) plt.xlabel("arcsec", fontsize=textsize) ax = plt.gca() divider = mplax.make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cticks = np.array([limits[0], np.sum(limits)/2, limits[1]]) cb = plt.colorbar(img, cax = cax, ticks = cticks) ax.tick_params(direction = 'in', which='both', right=True, top=True, labelleft=False, labelsize=digitsize) ax.set_aspect('equal') cax.tick_params(direction = 'in', labelsize=digitsize*1.05)
def contour_paths(self, epsilon): '''Extract the polygon patches for the provided epsilon''' figure = pyplot.figure() contours = pyplot.tricontour(self.triang, self.vals, levels=[epsilon]) paths = Paths() if len(contours.collections) == 0: return paths for path in contours.collections[0].get_paths(): paths.append(Path(path.vertices[:, 0] + 1j*path.vertices[:, 1])) pyplot.close(figure) return paths
def plot_contour(self, **kwargs): """Contour plot of the xy plane Parameters ---------- **kwargs Forwarded to `plt.tricontour()`. """ x, y, _ = self.pos contour = plt.tricontour(x, y, self.data, **kwargs) self._decorate_plot() return contour
def test_tri_smooth_contouring(): # Image comparison based on example tricontour_smooth_user. n_angles = 20 n_radii = 10 min_radius = 0.15 def z(x, y): r1 = np.sqrt((0.5 - x) ** 2 + (0.5 - y) ** 2) theta1 = np.arctan2(0.5 - x, 0.5 - y) r2 = np.sqrt((-x - 0.2) ** 2 + (-y - 0.2) ** 2) theta2 = np.arctan2(-x - 0.2, -y - 0.2) z = -( 2 * (np.exp((r1 / 10) ** 2) - 1) * 30.0 * np.cos(7.0 * theta1) + (np.exp((r2 / 10) ** 2) - 1) * 30.0 * np.cos(11.0 * theta2) + 0.7 * (x ** 2 + y ** 2) ) return (np.max(z) - z) / (np.max(z) - np.min(z)) # First create the x and y coordinates of the points. radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0 + n_angles, 2 * np.pi + n_angles, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += np.pi / n_angles x0 = (radii * np.cos(angles)).flatten() y0 = (radii * np.sin(angles)).flatten() triang0 = mtri.Triangulation(x0, y0) # Delaunay triangulation z0 = z(x0, y0) xmid = x0[triang0.triangles].mean(axis=1) ymid = y0[triang0.triangles].mean(axis=1) mask = np.where(xmid * xmid + ymid * ymid < min_radius * min_radius, 1, 0) triang0.set_mask(mask) # Then the plot refiner = mtri.UniformTriRefiner(triang0) tri_refi, z_test_refi = refiner.refine_field(z0, subdiv=4) levels = np.arange(0.0, 1.0, 0.025) plt.triplot(triang0, lw=0.5, color="0.5") plt.tricontour(tri_refi, z_test_refi, levels=levels, colors="black")
def tricontourf_deformed(a, mesh, d, name, cmap, dpi, magf): """Plot contour with the tricoutour function and the boundary line with the boundary node. """ fig = plt.figure(name, dpi=dpi) ax1 = fig.add_subplot(1, 1, 1, aspect='equal') c = mesh.nodes_coord bn = mesh.boundary_nodes xx, yy, zz = c[:, 0]+d[::2]*magf, c[:, 1]+d[1::2]*magf, a dx = d[::2]*magf dy = d[1::2]*magf ccx = np.append(c[bn[:, 1], 0]+dx[bn[:, 1]], c[bn[0, 1], 0]+dx[bn[0, 1]]) ccy = np.append(c[bn[:, 1], 1]+dy[bn[:, 1]], c[bn[0, 1], 1]+dy[bn[0, 1]]) plt.plot(ccx, ccy, '-k') triangles = [] for n1, n2, n3, n4 in mesh.ele_conn: triangles.append([n1, n2, n3]) triangles.append([n1, n3, n4]) triangles = np.asarray(triangles) CS2 = plt.tricontourf(xx, yy, triangles, zz, N=10, origin='lower', cmap=cmap) CS3 = plt.tricontour(xx, yy, triangles, zz, N=10, origin='lower',colors='k') plt.xlabel(r'$x$', fontsize=14) plt.ylabel(r'$y$', fontsize=14) divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size=0.3, pad=0.1) cbar = plt.colorbar(CS2, cax=cax) cbar.ax.set_label(name, fontsize=12) plt.clabel(CS3, fontsize=8, colors='k', fmt='%1.1f') limits=plt.axis('off') # plt.savefig('1.png', transparent=True, dpi=300) #plt.axes().set_aspect('equal') #plt.axes().autoscale_view(True, True, True) plt.draw()
def plot(self, epsilons, **kwargs): epsilons = list(numpy.sort(epsilons)) padepsilons = [epsilons[0]*0.9] + epsilons + [epsilons[-1]*1.1] X = [] Y = [] Z = [] for epsilon in padepsilons: paths = self.contour_paths(epsilon) for path in paths: X += list(numpy.real(path.vertices[:-1])) Y += list(numpy.imag(path.vertices[:-1])) Z += [epsilon] * (len(path.vertices) - 1) contours = pyplot.tricontour(X, Y, Z, levels=epsilons, colors=pyplot.rcParams['axes.color_cycle'] ) plot_finish(contours, **kwargs) return contours
def contour(self, prop=None): if(prop=='Tdust'): data=self.T[0:len(self.x)]['1'] label="Dust temperature [K]" elif(prop=='rho'): data=np.log(self.rho[0:len(self.x)]['1']) label="Log some density [?]" else: try: data=self.prop label='Unknown property' except: print "Please specify property to plot. Valid properties are [Tdust, rho]" return x_au = self.x/1.49e13 y_au = self.y/1.49e13 tri=Triangulation(x_au,y_au) plt.close('all') plt.figure() ax=plt.subplot(111) ax.set_xscale("log",nonposx='clip') ax.set_yscale("log",nonposy='clip') ax.set_xlim([0.1,200]) ax.set_ylim([0.1,200]) plt.xlabel('r [AU]') plt.ylabel('z [AU]') nmax=data.max() nmin=data.min() levels=np.arange(12) * (nmax-nmin)/12. + nmin plt.tricontourf(tri, data, levels) cbar=plt.colorbar() 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)
def computeContours(self): extend = str(self.uExtend.itemText(self.uExtend.currentIndex())) x, y, z = self._data levels = self.getLevels() if self._isMPLOk()==True: # If so, we can use the new tricontour fonction cs = plt.tricontour(x, y, z, levels, extend=extend) else: gx = x.reshape(self._nr,self._nc) gy = y.reshape(self._nr,self._nc) gz = z.reshape(self._nr,self._nc) cs = plt.contour(gx, gy, gz, levels, extend=extend) lines = list() levels = [float(l) for l in cs.levels] self.progressBar.setRange(0, len(cs.collections)) for i, line in enumerate(cs.collections): linestrings = [] for path in line.get_paths(): if len(path.vertices) > 1: linestrings.append(path.vertices) lines.append([ i, levels[i], linestrings]) self.progressBar.setValue(i+1) self.progressBar.setValue(0) return lines
def lineContourFeatures(self): x,y,z=self.data() levels = self.levels() usegrid=self.isGridded() and self._useGrid try: if usegrid: gx,gy,gz=self.gridContourData() cs = contour(gx, gy, gz, levels ) else: trig,z=self.trigContourData() cs = tricontour(trig, z, levels ) except: raise ContourGenerationError.fromException(sys.exc_info()) fields = self.fields() zfield=self.zFieldName() dx,dy=self._origin for i, line in enumerate(cs.collections): level=float(cs.levels[i]) glines = [] try: for path in line.get_paths(): if len(path.vertices) > 1: points=[QgsPointXY(x,y) for x,y in path.vertices] glines.append(points) geom=QgsGeometry.fromMultiPolylineXY(glines) geom.translate(dx,dy) feat = QgsFeature(fields) feat.setGeometry(geom) feat['index']=i feat[zfield]=level feat['label']=self._levelLabel(level) yield feat except: message=sys.exc_info()[1] self._feedback.reportError(message)
Xmax, Ymax = X[area_max].flat[amax], Y[area_max].flat[amax] lsteps_ = int(max(refi_magU[area_max])/lmax*lsteps) lx = Xmin + np.sign(Xmax-Xmin)*np.linspace(0, abs(Xmax-Xmin)**(1./args.lpow), 1 + lsteps_)**args.lpow ly = Ymin + np.sign(Ymax-Ymin)*np.linspace(0, abs(Ymax-Ymin)**(1./args.lpow), 1 + lsteps_)**args.lpow #plt.plot(lx, ly, '*') lx, ly = (lx[1:] + lx[:-1])/2, (ly[1:] + ly[:-1])/2 #plt.plot(lx, ly, 'D') labelpos = tuple(map(tuple, np.vstack((lx,ly)).T)) linewidth, fontsize = .5, 6 ### Plot detailed contours refi_magU = np.maximum(refi_magU, lmin) dl, ds = ((lmax-lmin)/lsteps/2,1) if np.max(magU) > lmax else (0,0) levels = np.linspace(lmin, lmax + dl, 1 + 2*lsteps + ds) if grayscale: plt.tricontour(refi_triang, refi_magU, levels=levels, colors='lightgray', linewidths=0.05) else: cmap = cm.get_cmap('coolwarm') plt.tricontourf(refi_triang, refi_magU, cmap=cmap, levels=levels) ### Plot black contours with labels levels = np.linspace(lmin, lmax, 1 + lsteps) CS = plt.tricontour(refi_triang, refi_magU, levels=levels, colors='k', linewidths=.3) clabels = plt.clabel(CS, levels, inline=True, use_clabeltext=True, fmt='%g', manual=labelpos, fontsize=6) [ txt.set_backgroundcolor('white') for txt in clabels ] [ txt.set_bbox(dict(facecolor='white', edgecolor='none', pad=0.5)) for txt in clabels ]
# Mask off unwanted triangles. 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) #----------------------------------------------------------------------------- # Refine data #----------------------------------------------------------------------------- refiner = tri.UniformTriRefiner(triang) tri_refi, z_test_refi = refiner.refine_field(z, subdiv=3) #----------------------------------------------------------------------------- # Plot the triangulation and the high-res iso-contours #----------------------------------------------------------------------------- plt.figure() plt.gca().set_aspect('equal') plt.triplot(triang, lw=0.5, color='white') levels = np.arange(0., 1., 0.025) cmap = cm.get_cmap(name='terrain', lut=None) plt.tricontourf(tri_refi, z_test_refi, levels=levels, cmap=cmap) plt.tricontour(tri_refi, z_test_refi, levels=levels, colors=['0.25', '0.5', '0.5', '0.5', '0.5'], linewidths=[1.0, 0.5, 0.5, 0.5, 0.5]) plt.title("High-resolution tricontouring") plt.show()
start = time.clock() plt.subplot(211) xi = np.linspace(-2.1,2.1,ngridx) yi = np.linspace(-2.1,2.1,ngridy) zi = griddata(x,y,z,xi,yi,interp='linear') plt.contour(xi,yi,zi,15,linewidths=0.5,colors='k') plt.contourf(xi,yi,zi,15,cmap=plt.cm.rainbow, norm=plt.normalize(vmax=abs(zi).max(), vmin=-abs(zi).max())) plt.colorbar() # draw colorbar plt.plot(x, y, 'ko', ms=3) plt.xlim(-2,2) plt.ylim(-2,2) plt.title('griddata and contour (%d points, %d grid points)' % (npts, ngridx*ngridy)) print ('griddata and contour seconds: %f' % (time.clock() - start)) # tricontour. start = time.clock() plt.subplot(212) triang = tri.Triangulation(x, y) plt.tricontour(x, y, z, 15, linewidths=0.5, colors='k') plt.tricontourf(x, y, z, 15, cmap=plt.cm.rainbow, norm=plt.normalize(vmax=abs(zi).max(), vmin=-abs(zi).max())) plt.colorbar() plt.plot(x, y, 'ko', ms=3) plt.xlim(-2,2) plt.ylim(-2,2) plt.title('tricontour (%d points)' % npts) print ('tricontour seconds: %f' % (time.clock() - start)) plt.show()
plot_masked_tri = True # plot of the excessively flat excluded triangles plot_refi_tri = False # plot of the refined triangulation plot_expected = False # plot of the analytical function values for comparison # Graphical options for tricontouring levels = np.arange(0., 1., 0.025) cmap = cm.get_cmap(name='Blues', lut=None) plt.figure() plt.gca().set_aspect('equal') plt.title("Filtering a Delaunay mesh\n" + "(application to high-resolution tricontouring)") # 1) plot of the refined (computed) data countours: plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap, linewidths=[2.0, 0.5, 1.0, 0.5]) # 2) plot of the expected (analytical) data countours (dashed): if plot_expected: plt.tricontour(tri_refi, z_expected, levels=levels, cmap=cmap, linestyles='--') # 3) plot of the fine mesh on which interpolation was done: if plot_refi_tri: plt.triplot(tri_refi, color='0.97') # 4) plot of the initial 'coarse' mesh: if plot_tri: plt.triplot(tri, color='0.7') # 4) plot of the unvalidated triangles from naive Delaunay Triangulation: if plot_masked_tri: plt.triplot(flat_tri, color='red') plt.show()
print min(u), max(u),numpy.mean(u) if plotvec: vecx=ux ##/u; vecy=uy ##/u; plt.quiver(triang.x, triang.y, vecx, vecy,color='cyan',zorder=100) # scale=100,headlength=30,headwidth=30) #units='xy', scale=1000, zorder=1, color='blue', #width=1, headwidth=0.1, headlength=0.1) if plotcont: plt.tricontour(triang, z, levels=[0.25], #colors=['0.25', '0.5', '0.5', '0.5', '0.5'], cmap=cmap, linewidths=[1.0],zorder=50) if plottri: aa=1.0 im=plt.tricontourf(triang,z, levels=levels, cmap=cmap,alpha=aa) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.15) plt.colorbar(im, cax=cax) plt.title(label) fig.savefig(pngfile) fig.savefig(pdffile)
# Create the Triangulation; no triangles so Delaunay triangulation created. triang = tri.Triangulation(x, y) # Mask off unwanted triangles. 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) # pcolor plot. plt.figure() plt.gca().set_aspect('equal') plt.tricontourf(triang, z) plt.colorbar() plt.tricontour(triang, z, colors='k') plt.title('Contour plot of Delaunay triangulation') # You can specify your own triangulation rather than perform a Delaunay # triangulation of the points, where each triangle is given by the indices of # the three points that make up the triangle, ordered in either a clockwise or # anticlockwise manner. xy = np.asarray([ [-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888], [-0.054, 0.890], [-0.045, 0.897], [-0.057, 0.895], [-0.073, 0.900], [-0.087, 0.898], [-0.090, 0.904], [-0.069, 0.907], [-0.069, 0.921], [-0.080, 0.919], [-0.073, 0.928], [-0.052, 0.930], [-0.048, 0.942], [-0.062, 0.949], [-0.054, 0.958], [-0.069, 0.954], [-0.087, 0.952], [-0.087, 0.959], [-0.080, 0.966], [-0.085, 0.973], [-0.087, 0.965], [-0.097, 0.965], [-0.097, 0.975], [-0.092, 0.984], [-0.101, 0.980], [-0.108, 0.980],
print 'number of time steps:',len(time_var) itime = netCDF4.date2index(start,time_var,select='nearest') start_time = netCDF4.num2date(time_var[0],time_var.units) stop_time = netCDF4.num2date(time_var[-1],time_var.units) print 'start time:',start_time.strftime('%Y-%b-%d %H:%M') print 'stop time:',stop_time.strftime('%Y-%b-%d %H:%M') dtime = netCDF4.num2date(time_var[itime],time_var.units) daystr = dtime.strftime('%Y-%b-%d %H:%M') print 'time selected:', daystr # <codecell> z = ncv[zvar][itime,:] # <codecell> fig = plt.figure(figsize=(12,12)) levs = np.arange(-1,5,.2) plt.gca().set_aspect(1./np.cos(lat.mean()*np.pi/180)) plt.tricontourf(triang, z,levels=levs) plt.colorbar() plt.tricontour(triang, z, colors='k',levels=levs) plt.title('%s: Elevation (m): %s' % (nc.title,daystr)); # <codecell> # <codecell>
def contour(time_list, depth_list, dc_list, corr_list, beachball_list, plot_file): """ Plotting contour """ # sets figure's dimensions _fig_x = 60 _fig_y = 40 # creates figure fig, ax = plt.subplots(figsize=(_fig_x,_fig_y)) # creates a grid on the (main) plot ax.grid() # sets labels plt.xlabel('Time (sec)') plt.ylabel('Centroid Depth (km)') # sets font size plt.rcParams.update({'font.size': 28}) # sets margins on the plot plt.margins(0.05) tri.Triangulation(time_list, depth_list) levels=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] cont = plt.tricontour(time_list, depth_list, corr_list, len(levels), levels=levels, linewidths=0.5, colors='k') plt.tricontourf(time_list, depth_list, corr_list, len(levels), levels=levels, cmap=plt.cm.cool) plt.clabel(cont) cm=plt.cm.copper_r #gia dc # plotting beachballs on specific x-axis and y-axis # with a color based on the data_dc values (normalized to 0-1) _max_corr = max(corr_list) _index = corr_list.index(_max_corr) for i in xrange(len(beachball_list)): if i == _index: # sets best beachball's color value to red _color = 'red' _width = 45 # bigger beachball for best match else: # sets beachball's color value _color = cm(dc_list[i]/100.0) _width = 35 # draws beachball b = beach.beach([beachball_list[i][0], beachball_list[i][1], beachball_list[i][2]], xy=(time_list[i],depth_list[i]), width=_width, linewidth=1, facecolor=_color) # holds the aspect but fixes positioning: b.set_transform(transforms.IdentityTransform()) # brings the all patches to the origin (0, 0). for p in b._paths: p.vertices -= [time_list[i], depth_list[i]] # uses the offset property of the collection to position the patches b.set_offsets((time_list[i], depth_list[i])) b._transOffset = ax.transData # adds beachball to plot ax.add_collection(b) # creates a colorbar at the right of main plot divider = make_axes_locatable(ax) # makes room for colorbar cax = divider.append_axes("right", size="1%", pad=0.5) # set values to colorbar norm = colors.Normalize(vmin=0.0, vmax=1.0) # creates colorbar on specific axes, norm, canvas color and orientation colorbar.ColorbarBase(cax, cmap=plt.cm.cool, norm=norm, orientation='vertical', label='Correlation') cax = divider.append_axes("right", size="1%", pad=1.5) # set values to colorbar norm = colors.Normalize(vmin=0, vmax=100) # creates colorbar on specific axes, norm, canvas color and orientation colorbar.ColorbarBase(cax, cmap=plt.cm.copper_r , norm=norm, orientation='vertical', label='DC%') # save plot to file plt.savefig(plot_file, dpi=fig.dpi)
import matplotlib.pyplot as pt from mesh import make_mesh mesh = make_mesh() # {{{ find connectivity adjacency = {} for a, b, c in mesh.elements: for v1, v2 in [(a,b), (b,c), (c,a)]: for x, y in [(v1, v2), (v2, v1)]: adjacency.setdefault(v1, set()).add(v2) # }}} from pymetis import part_graph points = np.array(mesh.points) elements = np.array(mesh.elements) vweights = points[:,0]**2 cuts, part_vert = part_graph(2, adjacency, #vweights=[int(20*x) for x in vweights] ) pt.triplot(points[:, 0], points[:, 1], elements, color="black", lw=0.1) pt.tripcolor(points[:, 0], points[:, 1], elements, part_vert) pt.tricontour(points[:, 0], points[:, 1], elements, part_vert, colors="black", levels=[0]) pt.show()
import numpy as np import math # First create the x and y coordinates of the points. n_angles = 48 n_radii = 8 min_radius = 0.25 radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 2*math.pi, n_angles, endpoint=False) angles = np.repeat(angles[...,np.newaxis], n_radii, axis=1) angles[:,1::2] += math.pi/n_angles x = (radii*np.cos(angles)).flatten() y = (radii*np.sin(angles)).flatten() z = (np.cos(radii)*np.cos(angles*3.0)).flatten() # Create a custom triangulation triang = tri.Triangulation(x, y) # Mask off unwanted triangles. 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) plt.figure() plt.gca(projection='3d') plt.tricontour(triang, z) plt.show()
def writeContour(self): key = "CLsexp" if self.gridConfig.useDiscovery: key = "p0exp" self.writePreHook() x = np.array([p[self.gridConfig.x] for p in self.contourData.combinedData.values() if p[self.contourData.combineOn] is not None]) y = np.array([p[self.gridConfig.y] for p in self.contourData.combinedData.values() if p[self.contourData.combineOn] is not None]) z = np.array([p[self.contourData.combineOn] for p in self.contourData.combinedData.values() if p[self.contourData.combineOn] is not None]) if x.size == 0 or y.size == 0 or z.size == 0: print("No data points for for contour") return # Set up a regular grid of interpolation points xMin = 0 yMin = 0 xMax = x.max() yMax = y.max() # vertical levels array for the plot v = np.linspace(0, 1.0, 21, endpoint=True) plt.ioff() fig = plt.figure(figsize=(20,6)) ax = plt.subplot(111) triang = matplotlib.tri.Triangulation(x, y) CS = plt.tricontour(triang, z, v, linewidths=3.5, colors=('blue'), levels=[0.05]) plt.tricontourf(triang, z, v, cmap=plt.cm.jet_r) CB = plt.colorbar(ticks=v) lines = [CS.collections[0]] labels = ["Combined"] cmap = get_cmap(len(self.contourData.contributingRegions)) i=0 for f in self.contourData.contributingRegions: i+=1 rX = np.array([p[self.gridConfig.x] for p in self.contourData.data[f].values() if p[self.contourData.combineOn] is not None]) rY = np.array([p[self.gridConfig.y] for p in self.contourData.data[f].values() if p[self.contourData.combineOn] is not None]) rZ = np.array([p[self.contourData.combineOn] for p in self.contourData.data[f].values() if p[self.contourData.combineOn] is not None]) triang = matplotlib.tri.Triangulation(rX, rY) # we have exactly 1 contour, so set our tuple to that rCS = plt.tricontour(triang, rZ, v, linewidths=1.5, colors=(cmap(i),), linestyle='--', levels=[0.05]) label = filterLabel(f, self.gridConfig) labels.append(label) lines.append(rCS.collections[0]) plt.title('Optimisation result', weight='bold') plt.xlabel('%s [GeV]' % (self.gridConfig.x), position=(1,0), horizontalalignment='right', weight='bold') plt.ylabel('%s [GeV]' % (self.gridConfig.y), position=(0,1), horizontalalignment='right', weight='bold') (outputFilename, ext) = os.path.splitext(self.outputFilename) outputFilename = "%s.contour%s" % (outputFilename, ext) # Shrink current axis by 50% box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.5, box.height]) # Put a legend to the right of the current axis ax.legend(lines, labels, loc='center left', bbox_to_anchor=(1, 0.5), shadow=False, fontsize='x-small') #legend = plt.legend(lines, labels, loc='upper right', shadow=False, fontsize='x-small') if not os.path.exists(os.path.dirname(outputFilename)): print("Creating output dir {0}".format(os.path.dirname(outputFilename))) os.makedirs(os.path.dirname(outputFilename)) plt.savefig(outputFilename, close=False, verbose=True, bbox_inches='tight') print("\n=> Wrote contour to {0}".format(outputFilename))
sys.exit() else: print 'no valid .soln file' sys.exit() x = xy[:, 0] y = xy[:, 1] print 'solution has minimum %.6e, maximum %.6e' % (u.min(),u.max()) if (args.contours == np.nan): NC = 10 print 'plotting with %d automatic contours ...' % NC du = u.max() - u.min() C = np.linspace(u.min()+du/(2*NC),u.max()-du/(2*NC),NC) else: C = np.array(args.contours) plt.figure() plt.gca().set_aspect('equal') plt.tricontour(x, y, ele, u, C, colors='k', extend='neither', linewidths=0.5, linestyles='solid') plt.axis('off') if len(args.o) > 0: print 'saving contour map in %s ...' % args.o plt.savefig(args.o,bbox_inches='tight') else: print 'plotting to screen (-o not given) ...' plt.show()
# In[11]: zcube = cube[itime,klev] # In[12]: plt.figure(figsize=(16,6)) ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(bbox) ax.coastlines(resolution='10m') plt.tricontourf(triang, zcube.data, levels=levs) plt.colorbar(fraction=0.046, pad=0.04) plt.tricontour(triang, zcube.data, colors='k',levels=levs) tstr = tvar.units.num2date(tvar.points[itime]) gl = ax.gridlines(draw_labels=True) gl.xlabels_top = False gl.ylabels_right = False plt.title('%s: %s: %s' % (var,tstr,zcube.attributes['title'])); # In[13]: ucube = iris.load_raw(url,'eastward_sea_water_velocity')[0] vcube = iris.load_raw(url,'northward_sea_water_velocity')[0] # In[14]: