def show_uboxes(uboxes,S=None,col='b',ecol='k', fig=None): if uboxes.dim != 2: raise Exception("show_uboxes: dimension must be 2") if S is None: S = range(uboxes.size) patches = [] for i in S: art = mpatches.Rectangle(uboxes.corners[i],uboxes.width[0],uboxes.width[1]) patches.append(art) if not fig: fig = plt.figure() ax = fig.gca() ax.hold(True) collection = PatchCollection(patches) collection.set_facecolor(col) collection.set_edgecolor(ecol) ax.add_collection(collection,autolim=True) ax.autoscale_view() plt.draw() plt.show() return fig
def draw(self, ax, colour='k', alpha=1., linestyle='-', linewidth=1., markers=None, facecolor='none', dashes=(1, 1), zorder=0): """ Draw the polygon on ax """ # Add the last point ptstoplot = self.verts.tolist() ptstoplot.append(ptstoplot[0]) ptstoplot = np.array(ptstoplot) if facecolor == 'none': try: if linestyle == '--': ax.plot(ptstoplot[:, 0], ptstoplot[:, 1], c=colour, alpha=alpha, ls=linestyle, dashes=dashes, lw=linewidth, marker=markers, zorder=zorder) else: ax.plot(ptstoplot[:, 0], ptstoplot[:, 1], c=colour, alpha=alpha, ls=linestyle, lw=linewidth, marker=markers, zorder=zorder) except IndexError: pass else: patches = [] filled_pol = mp.Polygon(self.verts) patches.append(filled_pol) collection = PatchCollection(patches, facecolors=facecolor) ax.add_collection(collection) collection.set_alpha(alpha) collection.set_edgecolor(colour) collection.set_linewidth(linewidth) collection.set_linestyle(linestyle)
def color_split_bank_by_svd(filename_template, split_bank_nums, cm_min_vec, cm_max_vec, chi_min_vec, chi_max_vec): split_bank_nums = numpy.array(split_bank_nums) cm_min_vec = numpy.array(cm_min_vec) cm_max_vec = numpy.array(cm_max_vec) chi_min_vec = numpy.array(chi_min_vec) chi_max_vec = numpy.array(chi_max_vec) total_svd_banks = max(split_bank_nums) # Create rectangles for split-bank tiling plot patches = [] cm_range_vec = cm_max_vec-cm_min_vec chi_range_vec = chi_max_vec-chi_min_vec for cm_range, chi_range, cm_min, chi_min in zip(cm_range_vec, chi_range_vec, cm_min_vec, chi_min_vec): patches.append(Rectangle((cm_min, chi_min), cm_range, chi_range)) patches = numpy.array(patches) fig, axes = create_plot(r"$\mathcal{M} (M_{\odot})$", r"$\chi$", aspect = None) for n in range(total_svd_banks + 1): p = PatchCollection(patches[split_bank_nums == n], match_original=False, facecolor = choose_color(n), alpha=0.6) p.set_edgecolor('face') axes.add_collection(p) axes.set_xscale('log') axes.set_xlim(min(cm_min_vec), max(cm_max_vec)) axes.set_ylim(-1, 1) filename = filename_template % ("split_bank_color_by_svd",) fig.savefig(filename)
def show_uboxes_corners( corners, width, S=None, col='b', ecol='k' ): """ This version takes the corners and width arrays as arguments instead. """ if corners.ndim != 2: raise Exception("show_uboxes_corners: dimension must be 2") if S is None: S = range( len(corners) ) patches = [] for i in S: art = mpatches.Rectangle( corners[i], width[0], width[1] ) patches.append(art) fig = plt.figure() ax = fig.gca() ax.hold(True) collection = PatchCollection(patches) collection.set_facecolor(col) collection.set_edgecolor(ecol) ax.add_collection(collection,autolim=True) ax.autoscale_view() plt.show() return fig
def makePlot(F, V, field, varName, outCount, simTime, i_save): polygons = [] colors = [] maxVal = np.max(field) for fid in F.ids: #fid = 25 pos = np.full((3, 2), np.nan) for i in range(0, 3): pos[i, 0] = V.lons[F.Vids[fid, i]] pos[i, 1] = V.lats[F.Vids[fid, i]] lons = pos[:, 0] #print(np.std(lons)/F.nf) if F.nSubdiv == 0: thresh = 5 elif F.nSubdiv == 1: thresh = 1 elif F.nSubdiv == 2: thresh = 0.1 elif F.nSubdiv == 3: thresh = 0.05 elif F.nSubdiv == 4: thresh = 0.006 if np.std(lons) / F.nf > thresh: deltas = F.lons[fid] - lons condition = np.argwhere((np.abs(deltas) > np.std(lons)) & (lons != 180)) lons[condition] = lons[condition] + (np.sign(deltas) * 360)[condition] polygon = Polygon(pos, closed=True, linewidth=0) polygons.append(polygon) #colors.append(field[fid]/maxVal) colors.append(field[fid]) #pc = PatchCollection(polygons, alpha=0.8, cmap='copper') pc = PatchCollection(polygons, alpha=0.8) pc.set_edgecolor('k') pc.set_array(np.array(colors)) #fig,ax = plt.subplots(figsize=(20,12)) fig, ax = plt.subplots(figsize=(10, 6)) ax.set_xlim(-90, 540) ax.set_ylim(-90, 90) ax.add_collection(pc) fig.colorbar(pc, ax=ax) count = str(outCount).zfill(4) plt.title(count + ' ' + varName + ' day: ' + str(np.round(simTime / 3600 / 24, 2))) if i_save: name = 'out/' + varName + '_' + count + '.png' plt.savefig(name) plt.close('all') else: plt.show() #plt.subplots_adjust(0,0,1,1) return (plt, ax)
def add_blobs(rows, columns, sizes, color=None, ax=None): """The function draws circles around given pixel coordinates Parameters ----------- rows: array pixel positions, y axis columns: array pixel positions, x axis sizes:array Returns ------- star_circles: """ ax = ax or plt.gca() star_circles = PatchCollection([ Circle((col, row), radius=3 * sigma) for row, col, sigma in zip(rows, columns, sizes) ]) star_circles.set_facecolor('none') color = color or next(ax._get_lines.prop_cycler).get('color') star_circles.set_edgecolor(color) ax.add_collection(star_circles) return star_circles
def DrawPolygons(polygons): #https://stackoverflow.com/questions/32141476/how-to-fill-polygons-with-colors-based-on-a-variable-in-matplotlib font = {'family': 'serif', 'color': 'black', 'weight': 'normal', 'size': 14, } fig,ax = plt.subplots(figsize=(6, 6), dpi=80, facecolor='w', edgecolor='k') patches=[] for p in polygons: patches.append(Patches.Polygon(np.array(p),True)) p = PatchCollection(patches,cmap=matplotlib.cm.rainbow, alpha=0.8) p.set_edgecolor('k') colors = 10*np.random.random(len(patches)) p.set_array(np.array(colors)) ax.add_collection(p) fig.colorbar(p, ax=ax) plt.axis('equal') plt.gca().invert_xaxis() plt.title('Domain Decomposition Map (%d domains)' %(len(patches)), fontdict=font) plt.xlabel('X', fontdict=font) plt.ylabel('Y', fontdict=font) plt.show()
def custom_plot(image, box=None, polygons=None): #target.extra_fields['masks'].polygons è una lista in cui ogni elemento ha un .polygons # che è una lista di tensor fig, ax = plt.subplots(1) ax.imshow(image) if box is not None: for bb in box: rect = Rectangle((int(bb[0]), int(bb[1])), int(bb[2]), int(bb[3]), linewidth=1, edgecolor='r', facecolor='none') ax.add_patch(rect) if polygons is not None: patches = [] for p in polygons: for p2 in p.polygons: polygon = Polygon(p2.numpy().reshape((-1, 2)), False) patches.append(polygon) p = PatchCollection(patches, alpha=0.4) p.set_linewidth(2.0) p.set_edgecolor('r') ax.add_collection(p) plt.show()
def init_points(ax, points): pt_coll = PatchCollection(points, alpha=0.6) colors = ['limegreen'] * len(points) pt_coll.set_facecolors(colors) pt_coll.set_edgecolor('black') ax.add_collection(pt_coll) return pt_coll, colors
def visualize2D(ax,x,y,u,colorbarPosition='vertical',colorlimit=None): xdg0=np.vstack([x.flatten(order='C'),y.flatten(order='C')]) udg0=u.flatten(order='C') idx=np.asarray([0,1,3,2]) nelem=(x.shape[0]-1)*(x.shape[1]-1) nelemx=x.shape[1]-1; nelemy=x.shape[0]-1; nelem=nelemx*nelemy nnx=x.shape[1];nny=x.shape[0] e2vcg0=gen_e2vcg(x) udg_ref=udg0[e2vcg0] cmap=matplotlib.cm.coolwarm polygon_list=[] for i in range(nelem): polygon_=Polygon(xdg0[:,e2vcg0[idx,i]].T) polygon_list.append(polygon_) polygon_ensemble=PatchCollection(polygon_list,cmap=cmap,alpha=1) polygon_ensemble.set_edgecolor('face') polygon_ensemble.set_array(np.mean(udg_ref,axis=0)) if colorlimit is None: pass else: polygon_ensemble.set_clim(colorlimit) ax.add_collection(polygon_ensemble) ax.set_xlim(np.min(xdg0[0,:]),np.max(xdg0[0,:])) #ax.set_xticks([np.min(xdg0[0,:]),np.max(xdg0[0,:])]) ax.set_ylim(np.min(xdg0[1,:]),np.max(xdg0[1,:])) #ax.set_yticks([np.min(xdg0[1,:]),np.max(xdg0[1,:])]) #ax.set_aspect('equal') cbar=plt.colorbar(polygon_ensemble,orientation=colorbarPosition) return ax,cbar
def make_plot(self, val, cct, clm, cmap='jet', cmap_norm=None, cmap_vmin=None, cmap_vmax=None): # make color mapping smap = ScalarMappable(cmap_norm, cmap) smap.set_clim(cmap_vmin, cmap_vmax) smap.set_array(val) bin_colors = smap.to_rgba(val) # make patches patches = [] for i_c, i_clm in enumerate(clm): patches.append( Rectangle((i_clm[0], i_clm[2]), i_clm[1] - i_clm[0], i_clm[3] - i_clm[2])) patches_colle = PatchCollection(patches) patches_colle.set_edgecolor('face') patches_colle.set_facecolor(bin_colors) return patches_colle, smap
def update(self, frame): color = (0, 0, 0) p = PatchCollection([self.__array_polygons[frame]], alpha=.5) p.set_color(color) p.set_edgecolor([0, 0, 0]) self.__ax.add_collection(p) return
def plot_ax2_rejected(ax2): ax2.set_title('Points per\nrejected-cloud', pad=5, fontsize=SMALL_SIZE + 1) ax2.set_xlim(-0.1, 2.1) ax2.set_ylim(-0.1, 1.1) x_coord = np.linspace(0.0, 2.0, num=nrejected + 1) widths = x_coord[1:] - x_coord[:-1] patches = [] for i in range(nrejected): x_patch = x_coord[i] patches.append( mpatches.FancyBboxPatch( (x_patch, 0.0), widths[i], 1.0, boxstyle=mpatches.BoxStyle("Round", pad=0.0, rounding_size=0.2))) add_label(ax2, (x_patch + 0.5 * widths[i], 0.5), data_size[~ids_bool][i], color='white') if nrejected == 0: patches.append( mpatches.FancyBboxPatch( (0.0, 0.0), 2.0, 1.0, boxstyle=mpatches.BoxStyle("Round", pad=0.0, rounding_size=0.2))) add_label(ax2, (1.0, 0.5), 'None', color='black') collection = PatchCollection(patches, alpha=1.0) collection.set_edgecolor('k') collection.set_facecolor(colors_all[~ids_bool]) ax2.add_collection(collection) ax2.axis('off')
def make_transform_plot(self, fig, i, j, k, xlim, ylim, patches, value, bar=True): # plot a map of the transform value cmap = plt.cm.plasma_r ax = fig.add_subplot(i, j, k) ax.set_xlim(xlim) ax.set_ylim(ylim) LC = PatchCollection(patches, cmap=cmap) LC.set_array(value) LC.set_edgecolor('none') ax.add_collection(LC) if bar: fig.colorbar(LC) ax.set_aspect('equal') ax.patch.set_color([0.5, 0.5, 0.5]) ax.set_xticks([]) ax.set_yticks([]) return ax
def plot_tree(self): # 1: plot all datapoints keys = self.db.keys() data = np.asarray(self.db.query(keys)) # @todo change database info column = {"key": 0, "x": 1, "y": 2} if self.args.quadlevel: column["quad"] = 3 data = data[data[:, column["quad"]] < self.args.quadlevel] markersize = 0.5 if len(data) < 100: markersize = 4 plt.plot(data[:, column["x"]], data[:, column["y"]], 'ko', markersize=markersize) # 2: plot all boundingboxes/partitions bboxes = self.kdtree.partitions() patches = [] for b in bboxes[self.args.bbox_depth]: rect = plt.Rectangle(b.lower_left(), b.width(), b.height(), ec="none", edgecolor='black') patches.append(rect) # 3: show range query if self.args.range_query: rq = bb.BoundingBox.from_matrix(np.matrix(self.args.range_query)) patches.append( plt.Rectangle(rq.lower_left(), rq.width(), rq.height())) rkeys = self.kdtree.rquery(rq) NN = np.asarray(self.db.query(rkeys)) plt.plot(NN[:, column["x"]], NN[:, column["y"]], 'rs', markersize=markersize + 4) for point in NN: if rq.within(point[1], 0): if rq.within(point[2], 1): plt.plot([point[1]], [point[2]], 'bs', markersize=markersize + 4) colors = np.linspace(0, 100, len(patches) + 1) collection = PatchCollection(patches, cmap=plt.cm.jet, alpha=0.3) collection.set_edgecolor([0, 0, 0]) collection.set_array(np.array(colors)) self.ax.add_collection(collection)
def c(p): # where p is list of primitives # outputs a collecction of primitives. essentially takes union. can treat this as a new primitive coll = PatchCollection(p) coll.set_edgecolor('k') coll.set_facecolor([0, 0, 0, 0]) # coll.set_alpha(0.5) return coll
def grid_res(mesh_path, circumpolar=True, set_bound=False, bound=None, save=False, fig_name=None): # Plotting parameters if circumpolar: lat_max = -30 + 90 font_sizes = [30, 24, 20] # Build triangular patches for each element elements, patches = make_patches(mesh_path, circumpolar) # Calculate the grid resolution for each element values = [] for elm in elements: values.append(sqrt(elm.area()) * 1e-3) # Set up figure if circumpolar: fig = figure(figsize=(16, 12)) ax = fig.add_subplot(1, 1, 1, aspect='equal') else: fig = figure(figsize=(16, 8)) ax = fig.add_subplot(1, 1, 1) # Set colours for patches and add them to plot img = PatchCollection(patches, cmap=jet) img.set_array(array(values)) img.set_edgecolor('face') ax.add_collection(img) # Configure plot if circumpolar: xlim([-lat_max, lat_max]) ylim([-lat_max, lat_max]) ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_ticks([]) axis('off') else: xlim([-180, 180]) ylim([-90, 90]) ax.get_xaxis().set_ticks(arange(-120, 120 + 1, 60)) ax.get_yaxis().set_ticks(arange(-60, 60 + 1, 30)) title('Horizontal grid resolution (km)', fontsize=font_sizes[0]) if set_bound: cbar = colorbar(img, extend='max') else: cbar = colorbar(img) cbar.ax.tick_params(labelsize=font_sizes[2]) if set_bound: img.set_clim(vmin=0, vmax=bound) if save: fig.savefig(fig_name) else: fig.show()
def plot_bwtemp(x_min, x_max, y_min, y_max, gs, cbaxes, cbar_ticks, letter): # Set up a grey square to fill the background with land x_reg, y_reg = meshgrid(linspace(x_min, x_max, num=100), linspace(y_min, y_max, num=100)) land_square = zeros(shape(x_reg)) # Find bounds on variable in this region var_min, var_max = get_min_max(bwtemp_old, bwtemp_new, x_min, x_max, y_min, y_max, cavity=False) print 'Bounds on bottom temperature: ' + str(var_min) + ' ' + str(var_max) # Old simulation ax = subplot(gs[0, 0], aspect='equal') # Start with land background contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) # Add ocean elements img = PatchCollection(patches_all_old, cmap='jet') img.set_array(array(bwtemp_old)) img.set_edgecolor('face') img.set_clim(vmin=var_min, vmax=var_max) ax.add_collection(img) # Add ice shelf front contour lines contours_old = LineCollection(contour_lines_old, edgecolor='black', linewidth=1) ax.add_collection(contours_old) xlim([x_min, x_max]) ylim([y_min, y_max]) ax.set_xticks([]) ax.set_yticks([]) # Variable title title(letter + r') Bottom water temperature ($^{\circ}$C)', fontsize=18, loc='left') # New simulation ax = subplot(gs[0, 1], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(patches_all_new, cmap='jet') img.set_array(array(bwtemp_new)) img.set_edgecolor('face') img.set_clim(vmin=var_min, vmax=var_max) ax.add_collection(img) contours_new = LineCollection(contour_lines_new, edgecolor='black', linewidth=1) ax.add_collection(contours_new) xlim([x_min, x_max]) ylim([y_min, y_max]) ax.set_xticks([]) ax.set_yticks([]) # Colourbar cbar = colorbar(img, cax=cbaxes, ticks=cbar_ticks)
def init_polygons(ax): polygons = read.polygons() poly_coll = PatchCollection(polygons, alpha=0.6) poly_colors = plt.get_cmap('Pastel1')(np.arange(.10, 1.99, .24)) poly_coll.set_facecolors(poly_colors) poly_coll.set_edgecolor('black') ax.add_collection(poly_coll) return poly_coll, poly_colors
def plot_polygons(self): colors = 100 * np.random.rand(len(self.__array_polygons)) p = PatchCollection(self.__array_polygons, alpha=.5) p.set_array(np.array(colors)) p.set_edgecolor([0, 0, 0]) self.__ax.set_xlim((0, self.__x_lim)) self.__ax.set_ylim((0, self.__y_lim)) self.__ax.set_title(self.__title) self.__ax.add_collection(p) plt.show()
def plot_quadtree(self): qt_depth = max(self.quadtree.quads.keys()) patches = [] for q in self.quadtree.quads[qt_depth]: rect = plt.Rectangle(q.lower_left(), q.width(), q.height()) patches.append(rect) collection = PatchCollection(patches) collection.set_edgecolor([0, 0, 0]) self.ax.add_collection(collection)
def update(self, element: Element, time: Timestamp, µcluster: MicroCluster, clusters: Optional[list[Cluster]], unclustered: Optional[Set[MicroCluster]], eliminated: Optional[Set[MicroCluster]]): max_density = max( [µcluster.density(time) for µcluster in self.dyclee.all_µclusters]) if µcluster in self.patch_map: self.patch_map[µcluster].remove() patch_collection = PatchCollection([ Rectangle( µcluster.centroid - µcluster.context.hyperbox_lengths / 2, *µcluster.context.hyperbox_lengths) ]) patch_collection.set_edgecolor('w') patch_collection.set_facecolor( (0, 0, 0, 0.5 * µcluster.density(time) / max_density)) self.patch_map[µcluster] = patch_collection self.ax.add_collection(patch_collection) if clusters is not None: for cluster in clusters: for µcluster in cluster.µclusters: self.patch_map[µcluster].set_edgecolor( self.colour_manager.get_colour(cluster.label)) self.patch_map[µcluster].set_facecolor( (0, 0, 0, 0.5 * µcluster.density(time) / max_density)) order = sorted(range(len(clusters)), key=lambda i: clusters[i].label) self.ax.legend([ Rectangle((0, 0), 1, 1, facecolor='none', edgecolor=self.colour_manager.get_colour( clusters[i].label)) for i in order ], [clusters[i].label for i in order], loc=self.legend_loc) if unclustered is not None: for µcluster in unclustered: self.patch_map[µcluster].set_edgecolor( self.colour_manager.get_colour(µcluster.label, self.unclustered_opacity)) self.patch_map[µcluster].set_facecolor( (0, 0, 0, 0.5 * µcluster.density(time) / max_density)) if eliminated is not None: for µcluster in eliminated: self.patch_map[µcluster].remove() del self.patch_map[µcluster]
def plot_mask (mesh_path, circumpolar): # Plotting parameters if circumpolar: lat_max = -30 + 90 # Build triangular patches for each element elements, patches = make_patches(mesh_path, circumpolar) # Read mask f = open(mesh_path + 'ssrestoring_mask.out', 'r') node_mask = [] for line in f: node_mask.append(float(line)) f.close() # Apply to elements mask = [] for elm in elements: # For the purposes of plotting, unmask the element if at least 2 of the # 3 component nodes are unmasked if sum([node_mask[elm.nodes[0].id], node_mask[elm.nodes[1].id], node_mask[elm.nodes[2].id]]) >= 2: # Unmask this element mask.append(1) else: # Mask this element mask.append(0) # Set up figure fig = figure(figsize=(12, 9)) if circumpolar: ax = fig.add_subplot(1,1,1, aspect='equal') else: ax = fig.add_subplot(1,1,1) # Set colours for patches and add them to plot img = PatchCollection(patches, cmap=jet) img.set_array(array(mask)) img.set_edgecolor('face') ax.add_collection(img) # Configure plot if circumpolar: xlim([-lat_max, lat_max]) ylim([-lat_max, lat_max]) else: xlim([-180, 180]) ylim([-90, 90]) ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_ticks([]) title('Restoring mask') cbar = colorbar(img) img.set_clim(vmin=0, vmax=1) axis('off') show()
def add_circles(self, ax, centers, radis): circles = [] for c, r in zip(centers, radis): circles.append(patches.Circle(tuple(c), r)) patch_collection = PatchCollection(circles) patch_collection.set_facecolor("none") patch_collection.set_edgecolor("blue") patch_collection.set_linewidth(1.5) patch_collection.set_linestyle("dashed") ax.add_collection(patch_collection) print "added %d circles" % len(circles)
def plot_polygons(self): p = PatchCollection(self.__array_polygons, alpha=.5) p.set_facecolor([0, 0, 0]) p.set_edgecolor([0, 0, 0]) self.__ax.set_xlim((0, self.__x_lim)) self.__ax.set_ylim((0, self.__y_lim)) self.__ax.set_title(self.__title) self.__ax.add_collection(p) plt.axis('off') plt.title('') plt.plot() plt.savefig('Results/' + self.__title, bbox_inches='tight', pad_inches=0)
def paw_plot(sdata=None, sdata_bg=None, cdata=None, cmap=None, clim=None, edgecolor='#555555', bgcolor='#cccccc', legend=True, ax=None): ax = ax if ax else plt.gca() r = np.array([ 0, 1, 1, 1, 1, 1 ]) theta = np.array([ 0, 30, 75, 120, 165, 210 ]) * np.pi / 180.0 theta = np.array([ -5, 25, 70, 115, 160, 205 ]) * np.pi / 180.0 # theta = np.array([ 0, 30, 72, 114, 156, 198 ]) * np.pi / 180.0 if sdata is None: sdata = np.array([4,1,1,1,1,1])*.08 if cdata is None: cdata = np.ones(len(r)) if cmap is None: cmap = 'magma' if clim is None: clim = [0,1] xx = r * np.cos(theta) yy = r * np.sin(theta) patches = [ mpatch.Circle((x,y),rad) for (x,y,rad) in zip(xx,yy,np.sqrt(sdata)) ] col = PatchCollection(patches, zorder=2) col.set_array(cdata) col.set_cmap(cmap) col.set_edgecolor(edgecolor) col.set_clim(vmin=clim[0], vmax=clim[1]) ax.add_patch(mpatch.Arc((0.0, 0.0), 2.0, 2.0, angle=0.0, theta1=theta[1]*180.0/np.pi, theta2=theta[-1]*180.0/np.pi, edgecolor=edgecolor,facecolor='none', zorder=0, linestyle='--')) ax.add_collection(col) if legend: plt.colorbar(col) if sdata_bg is not None: patches = [ mpatch.Circle((x,y),rad) for (x,y,rad) in zip(xx,yy,np.sqrt(sdata_bg)) ] col = PatchCollection(patches, zorder=1) col.set_edgecolor(edgecolor) col.set_facecolor(bgcolor) ax.add_collection(col) ax.axis('equal') ax.axis('off') ax.set_xlim([-1.2,1.2]) ax.set_ylim([-.8,1.35])
def draw1DColumn(ax, x, val, thk, width=30, ztopo=0, cmin=1, cmax=1000, cmap=None, name=None, textoffset=0.0): """Draw a 1D column (e.g., from a 1D inversion) on a given ax. Examples -------- >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from pygimli.mplviewer import draw1DColumn >>> thk = [1, 2, 3, 4] >>> val = thk >>> fig, ax = plt.subplots() >>> draw1DColumn(ax, 0.5, val, thk, width=0.1, cmin=1, cmax=4, name="VES") <matplotlib.collections.PatchCollection object at ...> >>> ax.set_ylim(-np.sum(thk), 0) (-10, 0) """ z = -np.hstack((0., np.cumsum(thk), np.sum(thk) * 1.5)) + ztopo recs = [] for i in range(len(val)): recs.append(Rectangle((x - width / 2., z[i]), width, z[i + 1] - z[i])) pp = PatchCollection(recs) col = ax.add_collection(pp) pp.set_edgecolor(None) pp.set_linewidths(0.0) if cmap is not None: if isinstance(cmap, str): pp.set_cmap(pg.mplviewer.cmapFromName(cmap)) else: pp.set_cmap(cmap) pp.set_norm(colors.LogNorm(cmin, cmax)) pp.set_array(np.array(val)) pp.set_clim(cmin, cmax) if name: ax.text(x + textoffset, ztopo, name, ha='center', va='bottom') updateAxes_(ax) return col
def draw_bboxes(bboxes, ax=None, color='red', linewidth=1, **kw): if ax is None: ax = plt.gca() patches = [ mpatches.Rectangle((i[1], i[0]), i[3] - i[1], i[2] - i[0]) for i in bboxes ] boxcoll = PatchCollection(patches, **kw) boxcoll.set_facecolor('none') boxcoll.set_edgecolor(color) boxcoll.set_linewidth(linewidth) ax.collections = [] ax.add_collection(boxcoll)
def get_shape_collections(data: Dict): shapes = [] for points in data.values(): shapes.append( Polygon(np.array([points['lons'], points['lats']]).T, closed=True)) collection = PatchCollection(shapes) collection.set_facecolor('#eeeeee') collection.set_edgecolor('black') collection.set_linewidth(0.2) return collection
def plot_depth (mesh_path, fig_name, circumpolar=True): # Plotting parameters if circumpolar: lat_max = -30 + 90 font_sizes = [240, 192, 160] else: font_sizes = [30, 24, 20] # Build triangular patches for each element elements, patches = make_patches(mesh_path, circumpolar) # Find the depth of each element elm_depth = [] for elm in elements: depth1 = (elm.nodes[0].find_bottom()).depth depth2 = (elm.nodes[1].find_bottom()).depth depth3 = (elm.nodes[2].find_bottom()).depth elm_depth.append(mean(array([depth1, depth2, depth3]))) # Set up figure if circumpolar: fig = figure(figsize=(128, 96)) ax = fig.add_subplot(1,1,1, aspect='equal') else: fig = figure(figsize=(16, 8)) ax = fig.add_subplot(1,1,1) # Set colours for patches and add them to plot img = PatchCollection(patches, cmap=jet) img.set_array(array(elm_depth)) img.set_edgecolor('face') ax.add_collection(img) # Configure plot if circumpolar: xlim([-lat_max, lat_max]) ylim([-lat_max, lat_max]) ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_ticks([]) axis('off') else: xlim([-180, 180]) ylim([-90, 90]) ax.get_xaxis().set_ticks(arange(-120,120+1,60)) ax.get_yaxis().set_ticks(arange(-60,60+1,30)) title('Seafloor depth (m)', fontsize=font_sizes[0]) cbar = colorbar(img) cbar.ax.tick_params(labelsize=font_sizes[2]) img.set_clim(vmin=0, vmax=max(elm_depth)) savefig(fig_name)
def wedgeplt(x_axis, y_axis, label, x_i, y_i, rotor, tur_id, patches, image_property, save_path): """ 用于【单机位点】尾流影响扇区/测试扇区示意图绘制 :param x_axis: 全场机位x,平面经度坐标,list/series :param y_axis: 全场机位y,平面经度坐标,list/series :param label: 全场机位编号,list/series :param x_i: 对应绘制扇区机位i,平面经度坐标x,float :param y_i: 对应绘制扇区机位i,平面经度坐标y,float :param rotor: 对应绘制扇区机位i的叶轮直径,list/series :param tur_id: 对应绘制扇区机位i的机位编号,str :param patches:存储楔形wedge :param image_property: str, 尾流影响wake-influenced/测试自由流free-flow扇区 :param save_path: 存储路径 :return: """ fig = plt.figure(figsize=(12, 6), tight_layout=True) ax1 = fig.add_subplot(1, 1, 1) tursite = ax1.scatter(x_axis, y_axis, marker='^', s=20, label='Center') ax1.set_title('{} Turbine {} Sector(s) Display'.format( tur_id, image_property), fontsize=20) for i in range(0, len(x_axis)): # 标注机位编号 ax1.text(x_axis[i], y_axis[i], label[i]) p = PatchCollection(patches, alpha=0.6) if image_property == 'wake-influenced': # p.set_color(c='orange') # Set both the edgecolor and the facecolor. p.set_edgecolor(c=None) p.set_facecolor(c='orange') legend_patch = mpatches.Patch( color='orange', label='wake-influenced sectors') # 创建特殊的artists,添加到图例中 elif image_property == 'free-flow': # p.set_color(c='green') p.set_edgecolor(c=None) p.set_facecolor(c='green') legend_patch = mpatches.Patch(color='green', label='free-flow sectors') ax1.add_collection(p) ax1.legend(handles=[tursite, legend_patch], fontsize=10, loc='lower left') # 指定legend的位置 ax1.set_aspect('equal') # fig.colorbar(p, ax=ax1) fig.savefig(os.path.join( save_path, '{}机位{}扇区示意图.png'.format(tur_id, str(image_property))), transparent=True) # 保存背景为透明图片 # plt.show() plt.close("all")
def plot_depth(mesh_path, fig_name, circumpolar=True): # Plotting parameters if circumpolar: lat_max = -30 + 90 font_sizes = [240, 192, 160] else: font_sizes = [30, 24, 20] # Build triangular patches for each element elements, patches = make_patches(mesh_path, circumpolar) # Find the depth of each element elm_depth = [] for elm in elements: depth1 = (elm.nodes[0].find_bottom()).depth depth2 = (elm.nodes[1].find_bottom()).depth depth3 = (elm.nodes[2].find_bottom()).depth elm_depth.append(mean(array([depth1, depth2, depth3]))) # Set up figure if circumpolar: fig = figure(figsize=(128, 96)) ax = fig.add_subplot(1, 1, 1, aspect='equal') else: fig = figure(figsize=(16, 8)) ax = fig.add_subplot(1, 1, 1) # Set colours for patches and add them to plot img = PatchCollection(patches, cmap=jet) img.set_array(array(elm_depth)) img.set_edgecolor('face') ax.add_collection(img) # Configure plot if circumpolar: xlim([-lat_max, lat_max]) ylim([-lat_max, lat_max]) ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_ticks([]) axis('off') else: xlim([-180, 180]) ylim([-90, 90]) ax.get_xaxis().set_ticks(arange(-120, 120 + 1, 60)) ax.get_yaxis().set_ticks(arange(-60, 60 + 1, 30)) title('Seafloor depth (m)', fontsize=font_sizes[0]) cbar = colorbar(img) cbar.ax.tick_params(labelsize=font_sizes[2]) img.set_clim(vmin=0, vmax=max(elm_depth)) savefig(fig_name)
def zoneLines(self, edgecolour='black'): #was 'red' """ Set boundary colour for defined ESRI shapes edgecolour -- HTML colour name for boundary """ pc2 = PatchCollection(self.patches, match_original=True) pc2.set_facecolor('none') pc2.set_edgecolor(edgecolour) pc2.set_alpha(0.5) #5.0 pc2.set_linewidth(0.5) pc2.set_zorder(25) # 500 sq2 = self.ax.add_collection(pc2)
def plot_num_layers (mesh_path, fig_name): # Plotting parameters circumpolar = True lat_max = -30 + 90 font_sizes = [240, 192, 160] # Build triangular patches for each element elements, patches = make_patches(mesh_path, circumpolar) # Calculate the number of layers for each element num_layers = [] for elm in elements: num_layers_elm = 0 # Count the number of layers for each node for i in range(3): node = elm.nodes[i] num_layers_node = 1 # Iterate until we reach the bottom while node.below is not None: num_layers_node += 1 node = node.below num_layers_elm = max(num_layers_elm, num_layers_node) # Save the maximum number of layers across the 3 nodes num_layers.append(num_layers_elm) # Set up figure fig = figure(figsize=(128, 96)) ax = fig.add_subplot(1,1,1, aspect='equal') # Set colours for patches and add them to plot img = PatchCollection(patches, cmap=jet) img.set_array(array(num_layers)) img.set_edgecolor('face') ax.add_collection(img) # Configure plot xlim([-lat_max, lat_max]) ylim([-lat_max, lat_max]) ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_ticks([]) title('Ice shelf draft (m)', fontsize=font_sizes[0]) cbar = colorbar(img) cbar.ax.tick_params(labelsize=font_sizes[2]) img.set_clim(vmin=1, vmax=47) axis('off') savefig(fig_name)
def _get_fpt_ell_collection(dm, fpts, T_data, alpha, edgecolor): ell_patches = [] for (x, y, a, c, d) in fpts: # Manually Calculated sqrtm(inv(A)) with catch_warnings(): simplefilter("ignore") aIS = 1 / sqrt(a) cIS = (c / sqrt(a) - c / sqrt(d)) / (a - d + eps(1)) dIS = 1 / sqrt(d) transEll = Affine2D([(aIS, 0, x), (cIS, dIS, y), (0, 0, 1)]) unitCirc1 = Circle((0, 0), 1, transform=transEll) ell_patches = [unitCirc1] + ell_patches ellipse_collection = PatchCollection(ell_patches) ellipse_collection.set_facecolor("none") ellipse_collection.set_transform(T_data) ellipse_collection.set_alpha(alpha) ellipse_collection.set_edgecolor(edgecolor) return ellipse_collection
def animate(i): [c.remove() for c in ax.collections] patches = [] for (x, y), w in np.ndenumerate(matricies[i]): if w != 0.0: patches.append(Rectangle([x - boxsize / 2, y - boxsize / 2], boxsize, boxsize, fc=colourmap(w), ec='black')) colors = np.logspace(10e-30, 1, 100, endpoint=True) p = PatchCollection(patches) p.set_edgecolor('black') p.set_array(np.array(colors)) ax.add_collection(p) return ax,
class ArrayDisplay: """ Display a top-town view of a telescope array """ def __init__(self, telx, tely, mirrorarea, axes=None, title="Array", autoupdate=True): patches = [Circle(xy=(x, y), radius=np.sqrt(a)) for x, y, a in zip(telx, tely, mirrorarea)] self.autoupdate = autoupdate self.telescopes = PatchCollection(patches) self.telescopes.set_clim(0, 100) self.telescopes.set_array(np.zeros(len(telx))) self.telescopes.set_cmap('spectral_r') self.telescopes.set_edgecolor('none') self.axes = axes if axes is not None else plt.gca() self.axes.add_collection(self.telescopes) self.axes.set_aspect(1.0) self.axes.set_title(title) self.axes.set_xlim(-1000, 1000) self.axes.set_ylim(-1000, 1000) self.bar = plt.colorbar(self.telescopes) self.bar.set_label("Value") @property def values(self): """An array containing a value per telescope""" return self.telescopes.get_array() @values.setter def values(self, values): """ set the telescope colors to display """ self.telescopes.set_array(values) self._update() def _update(self): """ signal a redraw if necessary """ if self.autoupdate: plt.draw()
def bwsalt (mesh_path, file_path, save=False, fig_name=None): # Plotting parameters lat_max = -30 + 90 circumpolar=True # Build FESOM mesh elements, patches = make_patches(mesh_path, circumpolar) # Calculate annual average of bottom water temperature file = Dataset(file_path, 'r') data = mean(file.variables['salt'][:,:], axis=0) file.close() values = [] # Loop over elements for elm in elements: values_tmp = [] # For each component node, find the bottom index; average over # all 3 such indices to get the value for this element for node in elm.nodes: id = node.find_bottom().id values_tmp.append(data[id]) values.append(mean(values_tmp)) # Plot fig = figure(figsize=(16,12)) ax = fig.add_subplot(1,1,1,aspect='equal') img = PatchCollection(patches, cmap=jet) img.set_array(array(values)) img.set_edgecolor('face') img.set_clim(vmin=34, vmax=35) ax.add_collection(img) xlim([-lat_max, lat_max]) ylim([-lat_max, lat_max]) axis('off') title(r'Bottom water temperature ($^{\circ}$C), annual average', fontsize=30) cbar = colorbar(img) cbar.ax.tick_params(labelsize=20) if save: fig.savefig(fig_name) else: fig.show()
def draw1DColumn(ax, x, val, thk, width=30, ztopo=0, cmin=1, cmax=1000, cmap=None, name=None, textoffset=0.0): """Draw a 1D column (e.g., from a 1D inversion) on a given ax. Examples -------- >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from pygimli.mplviewer import draw1DColumn >>> thk = [1, 2, 3, 4] >>> val = thk >>> fig, ax = plt.subplots() >>> draw1DColumn(ax, 0.5, val, thk, width=0.1, cmin=1, cmax=4, name="VES") <matplotlib.collections.PatchCollection object at ...> >>> ax.set_ylim(-np.sum(thk), 0) (-10, 0) """ z = -np.hstack((0., np.cumsum(thk), np.sum(thk) * 1.5)) + ztopo recs = [] for i in range(len(val)): recs.append(Rectangle((x - width / 2., z[i]), width, z[i + 1] - z[i])) pp = PatchCollection(recs) col = ax.add_collection(pp) pp.set_edgecolor(None) pp.set_linewidths(0.0) if cmap is not None: if isinstance(cmap, str): pp.set_cmap(pg.mplviewer.cmapFromName(cmap)) else: pp.set_cmap(cmap) pp.set_norm(colors.LogNorm(cmin, cmax)) pp.set_array(np.array(val)) pp.set_clim(cmin, cmax) if name: ax.text(x+textoffset, ztopo, name, ha='center', va='bottom') updateAxes_(ax) return col
def plot_shelf (mesh_path, fig_name): # Plotting parameters circumpolar = True lat_max = -30 + 90 font_sizes = [240, 192, 160] # Build triangular patches for each element elements, patches = make_patches(mesh_path, circumpolar) # Find the ice shelf draft at each element # (i.e. depth of surface nodes in ice shelf cavities) elm_shelf = [] for elm in elements: if elm.cavity: shelf1 = (elm.nodes[0]).depth shelf2 = (elm.nodes[1]).depth shelf3 = (elm.nodes[2]).depth elm_shelf.append(mean(array([shelf1, shelf2, shelf3]))) else: elm_shelf.append(0.0) # Set up figure fig = figure(figsize=(128, 96)) ax = fig.add_subplot(1,1,1, aspect='equal') # Set colours for patches and add them to plot img = PatchCollection(patches, cmap=jet) img.set_array(array(elm_shelf)) img.set_edgecolor('face') ax.add_collection(img) # Configure plot xlim([-lat_max, lat_max]) ylim([-lat_max, lat_max]) ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_ticks([]) title('Ice shelf draft (m)', fontsize=font_sizes[0]) cbar = colorbar(img) cbar.ax.tick_params(labelsize=font_sizes[2]) axis('off') savefig(fig_name)
def plotGeometry(self, ax = None): if (ax is None): fig = plt.figure() ax = fig.add_subplot(111) ax.set_aspect(1) self.blockPatch.set_facecolor('#F0F0F0') self.blockPatch.set_edgecolor('k') ax.add_patch(self.blockPatch) pc = PatchCollection(self.channelPatches, match_original = True) pc.set_facecolor('w') pc.set_edgecolor('k') pc.set_zorder(2) ax.add_collection(pc) self.plotDimensions(ax) ax.set_xlim(self.xMin, self.xMax) ax.set_ylim(self.yMin, self.yMax) plt.show()
def show_box(b, col="b", ecol="k", alpha=1): patches = [] # lower left corner at b[0], followed by width and height xy = b[0] width = np.absolute(b[0, 1] - b[0, 0]) height = np.absolute(b[1, 1] - b[1, 0]) art = mpatches.Rectangle(xy, width, height) # art = mpatches.Rectangle(b[0],b[1,0],b[1,1]) patches.append(art) ax = plt.gca() ax.hold(True) collection = PatchCollection(patches) collection.set_facecolor(col) collection.set_edgecolor(ecol) collection.set_alpha(alpha) ax.add_collection(collection, autolim=True) ax.autoscale_view() plt.show()
def show_boxes(boxes, S=None, col="b", ecol="k", alpha=1): if boxes.dim != 2: raise Exception("show_boxes: dimension must be 2") if S is None: S = range(boxes.size) patches = [] for i in S: art = mpatches.Rectangle(boxes.corners[i], boxes.widths[i][0], boxes.widths[i][1]) patches.append(art) ax = plt.gca() ax.hold(True) collection = PatchCollection(patches) collection.set_facecolor(col) collection.set_edgecolor(ecol) collection.set_alpha(alpha) ax.add_collection(collection, autolim=True) ax.autoscale_view() plt.show()
def make_plot(self, val, cct, clm, cmap = 'jet', cmap_norm = None, cmap_vmin = None, cmap_vmax = None): # make color mapping smap = ScalarMappable(cmap_norm, cmap) smap.set_clim(cmap_vmin, cmap_vmax) smap.set_array(val) bin_colors = smap.to_rgba(val) # make patches patches = [] for i_c, i_clm in enumerate(clm): patches.append(Rectangle((i_clm[0], i_clm[2]), i_clm[1] - i_clm[0], i_clm[3] - i_clm[2])) patches_colle = PatchCollection(patches) patches_colle.set_edgecolor('face') patches_colle.set_facecolor(bin_colors) return patches_colle, smap
def show_box(b,col='b',ecol='k',alpha=1, fig=None): patches = [] # lower left corner at b[0], followed by width and height art = mpatches.Rectangle(b[0],b[1,0],b[1,1]) patches.append(art) if fig: ax = fig.gca() else: fig = plt.figure() ax = fig.gca() ax.hold(True) collection = PatchCollection(patches) collection.set_facecolor(col) collection.set_edgecolor(ecol) collection.set_alpha(alpha) ax.add_collection(collection,autolim=True) ax.autoscale_view() plt.show() return fig
def plot_cavityflag (mesh_path, fig_name): # Plotting parameters circumpolar = True lat_max = -30 + 90 font_sizes = [240, 192, 160] # Build triangular patches for each element elements, patches = make_patches(mesh_path, circumpolar) # For each element, get the cavity flag cavity = [] for elm in elements: if elm.cavity: cavity.append(1) else: cavity.append(0) # Set up figure fig = figure(figsize=(128, 96)) ax = fig.add_subplot(1,1,1, aspect='equal') # Set colours for patches and add them to plot img = PatchCollection(patches, cmap=jet) img.set_array(array(cavity)) img.set_edgecolor('face') ax.add_collection(img) # Configure plot xlim([-lat_max, lat_max]) ylim([-lat_max, lat_max]) ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_ticks([]) title('Ice shelf cavity flag', fontsize=font_sizes[0]) cbar = colorbar(img) cbar.ax.tick_params(labelsize=font_sizes[2]) img.set_clim(vmin=0, vmax=1) axis('off') savefig(fig_name)
def PlotCalibration(group, cal, mask): CalculateDIFC(InputWorkspace=group, CalibrationWorkspace=cal, OutputWorkspace='A') CalculateDIFC(InputWorkspace=group, OutputWorkspace='B') offset = 1 - mtd['A']/mtd['B'] #Accept either name or pointer to mask if isinstance(mask, six.string_types): mask = mtd[mask] #Calculate angles theta and phi from detector position. #Separate masked and unmasked detectors for plotting. #Offset values of unma]sked detectors are stored for plotting theta_array = [] phi_array = [] value_array = [] masked_theta_array = [] masked_phi_array = [] info = offset.spectrumInfo() for idx, x in enumerate(info): pos = x.position theta = np.arccos(pos[2] / pos.norm()) phi = np.arctan2(pos[1], pos[0]) if mask.dataY(idx): masked_theta_array.append(theta) masked_phi_array.append(phi) else: theta_array.append(theta) phi_array.append(phi) value_array.append(np.sum(offset.dataY(idx))) #Use the largest solid angle for circle radius sample_position = info.samplePosition() maximum_solid_angle = 0.0 for idx in six.moves.xrange(info.size()): maximum_solid_angle = max(maximum_solid_angle, offset.getDetector(idx).solidAngle(sample_position)) #Radius also includes a fudge factor to improve plotting. #May need to add finer adjustments on a per-instrument basis. #Small circles seem to alias less than rectangles. radius = maximum_solid_angle*8.0 patches = [] for x1, y1 in six.moves.zip(theta_array, phi_array): circle = Circle((x1, y1), radius) patches.append(circle) masked_patches = [] for x1, y1 in six.moves.zip(masked_theta_array, masked_phi_array): circle = Circle((x1, y1), radius) masked_patches.append(circle) #Matplotlib requires this to be a Numpy array. colors = np.array(value_array) p = PatchCollection(patches) p.set_array(colors) p.set_clim(-0.1,0.1) p.set_edgecolor('face') fig, ax = plt.subplots() ax.add_collection(p) mp = PatchCollection(masked_patches) mp.set_facecolor('gray') mp.set_edgecolor('face') ax.add_collection(mp) fig.colorbar(p, ax=ax) ax.set_xlabel(r'$\phi$') ax.set_xlim(0.0,np.pi) ax.set_ylabel(r'$\theta$') ax.set_ylim(-np.pi,np.pi) return fig, ax
def lonlat_plot( mesh_path, file_path, var_name, depth_key, depth, depth_bounds, tstep, circumpolar, elements, patches, mask_cavities=False, save=False, fig_name=None, set_limits=False, limits=None, ): # Set bounds for domain if circumpolar: # Northern boundary 30S lat_max = -30 + 90 else: lon_min = -180 lon_max = 180 lat_min = -90 lat_max = 90 # Configure position of latitude and longitude labels lon_ticks = arange(-120, 120 + 1, 60) lat_ticks = arange(-60, 60 + 1, 30) # Set font sizes font_sizes = [30, 24, 20] # Seconds per year, for conversion of ice shelf melt rate sec_per_year = 365 * 24 * 3600 # Read data file = Dataset(file_path, "r") varid = file.variables[var_name] data = varid[tstep - 1, :] # Check for vector variables that need to be unrotated if var_name in [ "uwind", "vwind", "stress_x", "stress_y", "uhice", "vhice", "uhsnow", "vhsnow", "uice", "vice", "u", "v", ]: # Read the rotated lat and lon if var_name in ["u", "v"]: # 3D variable mesh_file = mesh_path + "nod3d.out" else: # 2D variable mesh_file = mesh_path + "nod2d.out" fid = open(mesh_file, "r") fid.readline() lon = [] lat = [] for line in fid: tmp = line.split() lon_tmp = float(tmp[1]) lat_tmp = float(tmp[2]) if lon_tmp < -180: lon_tmp += 360 elif lon_tmp > 180: lon_tmp -= 360 lon.append(lon_tmp) lat.append(lat_tmp) fid.close() lon = array(lon) lat = array(lat) if var_name in ["uwind", "stress_x", "uhice", "uhsnow", "uice", "u"]: # u-variable u_data = data[:] if var_name == "stress_x": v_data = file.variables["stress_y"][tstep - 1, :] else: v_data = file.variables[var_name.replace("u", "v")][tstep - 1, :] u_data_lonlat, v_data_lonlat = unrotate_vector(lon, lat, u_data, v_data) data = u_data_lonlat[:] elif var_name in ["vwind", "stress_y", "vhice", "vhsnow", "vice", "v"]: # v-variable v_data = data[:] if var_name == "stress_y": u_data = file.variables["stress_x"][tstep - 1, :] else: u_data = file.variables[var_name.replace("v", "u")][tstep - 1, :] u_data_lonlat, v_data_lonlat = unrotate_vector(lon, lat, u_data, v_data) data = v_data_lonlat[:] # Set descriptive variable name and units for title if var_name == "area": name = "ice concentration" units = "fraction" elif var_name == "wnet": # Convert from m/s to m/y data = data * sec_per_year name = "ice shelf melt rate" units = "m/y" else: name = varid.getncattr("description") units = varid.getncattr("units") if depth_key == 0: if var_name in ["temp", "salt", "u", "v"]: depth_string = "at surface" else: depth_string = "" elif depth_key == 1: depth_string = "at bottom" elif depth_key == 2: depth_string = "vertically averaged" elif depth_key == 3: depth_string = "at " + str(depth) + " m" elif depth_key == 4: depth_string = "vertically averaged between " + str(depth_bounds[0]) + " and " + str(depth_bounds[1]) + " m" # Build an array of data values corresponding to each Element values = [] plot_patches = [] for elm in elements: # If mask_cavities is true, only include elements which are not inside # an ice shelf cavity; otherwise, include all elements if (mask_cavities and not elm.cavity) or (not mask_cavities): if depth_key == 0: # Surface nodes; this is easy # Average the data value for each of the three component nodes values.append(mean([data[elm.nodes[0].id], data[elm.nodes[1].id], data[elm.nodes[2].id]])) elif depth_key == 1: # Bottom nodes values_tmp = [] # For each of the three component nodes, find the id of the # bottom node beneath it for node in elm.nodes: id = node.find_bottom().id values_tmp.append(data[id]) # Average over these three values values.append(mean(values_tmp)) elif depth_key == 2: # Vertical average throughout entire water column # First calculate volume: area of triangular face * water # column thickness (mean of three corners) wct = [] for node in elm.nodes: wct.append(abs(node.find_bottom().depth - node.depth)) area = elm.area() volume = area * mean(array(wct)) # Now integrate down integral = 0 nodes = [elm.nodes[0], elm.nodes[1], elm.nodes[2]] while True: if nodes[0].below is None or nodes[1].below is None or nodes[2].below is None: break # Calculate mean of data at six corners of this triangular # prism, and mean depths at three edges values_tmp = [] dz_tmp = [] # Must loop over indices of nodes array, not entries, # because we want to change the contents of the nodes array for i in range(3): values_tmp.append(data[nodes[i].id]) values_tmp.append(data[nodes[i].below.id]) dz_tmp.append(abs(nodes[i].depth - nodes[i].below.depth)) # Get ready for next iteration of the while loop nodes[i] = nodes[i].below # Integrand is mean of data at corners * area of upper face # * mean of depths at edges integral += mean(array(values_tmp)) * area * mean(array(dz_tmp)) # All done; divide integral by volume to get the average values.append(integral / volume) elif depth_key == 3: # Specified depth values_tmp = [] # For each of the three component nodes, linearly interpolate # to the correct depth for i in range(3): # Find the ids of the nodes above and below this depth, # and the coefficients for the linear interpolation id1, id2, coeff1, coeff2 = elm.nodes[i].find_depth(depth) if any(isnan(array([id1, id2, coeff1, coeff2]))): # No such node at this depth values_tmp.append(NaN) else: values_tmp.append(coeff1 * data[id1] + coeff2 * data[id2]) if any(isnan(array(values_tmp))): pass else: values.append(mean(values_tmp)) coord = transpose(vstack((elm.x, elm.y))) # Make new patches for elements which exist at this depth plot_patches.append(Polygon(coord, True, linewidth=0.0)) elif depth_key == 4: # Vertical average between two specified depths shallow_bound = depth_bounds[0] deep_bound = depth_bounds[1] area = elm.area() # Volume is area of triangular face * difference between # depth bounds volume = abs(deep_bound - shallow_bound) * area nodes = [elm.nodes[0], elm.nodes[1], elm.nodes[2]] # Check if we're already too deep if nodes[0].depth > deep_bound or nodes[1].depth > deep_bound or nodes[2].depth > deep_bound: pass # Check if the seafloor is shallower than shallow_bound elif ( nodes[0].find_bottom().depth <= shallow_bound or nodes[1].find_bottom().depth <= shallow_bound or nodes[2].find_bottom().depth <= shallow_bound ): pass else: # Here we go # Find the first 3D element which is entirely below # shallow_bound while True: if ( nodes[0].depth > shallow_bound and nodes[1].depth > shallow_bound and nodes[2].depth > shallow_bound ): # Save these nodes first_nodes = [] for i in range(3): first_nodes.append(nodes[i]) break else: for i in range(3): nodes[i] = nodes[i].below # Integrate downward until one of the next nodes hits the # seafloor, or is deeper than deep_bound integral = 0 while True: if nodes[0].below is None or nodes[1].below is None or nodes[2].below is None: # We've reached the seafloor last_nodes = None break if ( nodes[0].below.depth > deep_bound or nodes[1].below.depth > deep_bound or nodes[2].below.depth > deep_bound ): # At least one of the next nodes will pass # deep_bound; save the current nodes last_nodes = [] for i in range(3): last_nodes.append(nodes[i]) break else: # Calculate mean of data at six corners of this # triangular prism, and mean depths at three edges values_tmp = [] dz_tmp = [] for i in range(3): values_tmp.append(data[nodes[i].id]) values_tmp.append(data[nodes[i].below.id]) dz_tmp.append(abs(nodes[i].depth - nodes[i].below.depth)) # Get ready for next iteration of while loop nodes[i] = nodes[i].below # Integrand is mean of data at corners * # area of upper face * mean of depths at edges integral += mean(array(values_tmp)) * area * mean(array(dz_tmp)) # Now integrate from shallow_bound to first_nodes by # linearly interpolating each node to shallow_bound values_tmp = [] dz_tmp = [] for i in range(3): values_tmp.append(data[first_nodes[i].id]) id1, id2, coeff1, coeff2 = elm.nodes[i].find_depth(shallow_bound) if any(isnan(array([id1, id2, coeff1, coeff2]))): # first_nodes[i] was the shallowest node, we can't # interpolate above it values_tmp.append(NaN) else: values_tmp.append(coeff1 * data[id1] + coeff2 * data[id2]) dz_tmp.append(abs(first_nodes[i].depth - shallow_bound)) if any(isnan(array(values_tmp))): pass else: integral += mean(array(values_tmp)) * area * mean(array(dz_tmp)) # Now integrate from last_nodes to deep_bound by linearly # interpolating each node to shallow_bound, unless we hit # the seafloor earlier if last_nodes is not None: values_tmp = [] dz_tmp = [] for i in range(3): values_tmp.append(data[last_nodes[i].id]) id1, id2, coeff1, coeff2 = elm.nodes[i].find_depth(deep_bound) if any(isnan(array([id1, id2, coeff1, coeff2]))): # last_nodes[i] was the deepest node, we can't # interpolate below it values_tmp.append(NaN) else: values_tmp.append(coeff1 * data[id1] + coeff2 * data[id2]) dz_tmp.append(abs(deep_bound - last_nodes[i].depth)) if any(isnan(array(values_tmp))): pass else: integral += mean(array(values_tmp)) * area * mean(array(dz_tmp)) # All done; divide integral by volume to get the average values.append(integral / volume) # Make new patches for elements which exist at this depth coord = transpose(vstack((elm.x, elm.y))) plot_patches.append(Polygon(coord, True, linewidth=0.0)) if depth_key < 3: # Use all patches plot_patches = patches[:] if mask_cavities: # Get mask array of patches for ice shelf cavity elements mask_patches = iceshelf_mask(elements) if var_name == "wnet": # Swap with regular patches so that open ocean elements are masked, # ice shelf cavity nodes are not tmp = plot_patches plot_patches = mask_patches mask_patches = tmp # Choose colour bounds if set_limits: # User-specified bounds var_min = limits[0] var_max = limits[1] if var_min == -var_max: # Bounds are centered on zero, so choose a blue-to-red colourmap # centered on yellow colour_map = "RdYlBu_r" else: colour_map = "jet" else: # Determine bounds automatically if var_name in [ "uwind", "vwind", "qnet", "olat", "osen", "wnet", "virtual_salt", "relax_salt", "stress_x", "stress_y", "uice", "vice", "u", "v", "w", ]: # Center levels on 0 for certain variables, with a blue-to-red # colourmap max_val = amax(abs(array(values))) var_min = -max_val var_max = max_val colour_map = "RdYlBu_r" else: var_min = amin(array(values)) var_max = amax(array(values)) colour_map = "jet" # Set up plot if circumpolar: fig = figure(figsize=(16, 12)) ax = fig.add_subplot(1, 1, 1, aspect="equal") else: fig = figure(figsize=(16, 8)) ax = fig.add_subplot(1, 1, 1) # Set colourmap for patches, and refer it to the values array img = PatchCollection(plot_patches, cmap=colour_map) img.set_array(array(values)) img.set_edgecolor("face") # Add patches to plot ax.add_collection(img) if mask_cavities: # Set colour to light grey for patches in mask overlay = PatchCollection(mask_patches, facecolor=(0.6, 0.6, 0.6)) overlay.set_edgecolor("face") # Add mask to plot ax.add_collection(overlay) # Configure plot if circumpolar: xlim([-lat_max, lat_max]) ylim([-lat_max, lat_max]) ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_ticks([]) axis("off") else: xlim([lon_min, lon_max]) ylim([lat_min, lat_max]) xticks(lon_ticks) yticks(lat_ticks) xlabel("Longitude", fontsize=font_sizes[1]) ylabel("Latitude", fontsize=font_sizes[1]) setp(ax.get_xticklabels(), fontsize=font_sizes[2]) setp(ax.get_yticklabels(), fontsize=font_sizes[2]) title(name + " (" + units + ") " + depth_string, fontsize=font_sizes[0]) cbar = colorbar(img) cbar.ax.tick_params(labelsize=font_sizes[2]) img.set_clim(vmin=var_min, vmax=var_max) # Plot specified points # problem_ids = [16, 17, 36, 64, 67, 70, 160, 262, 266, 267, 268, 273, 274, 280, 283, 287, 288, 289, 290, 291, 292, 293, 294, 296, 297, 350, 351, 352, 353, 360, 479, 480, 493, 507, 508, 509, 521, 539, 547, 548, 549, 550, 554, 555] # problem_x = [] # problem_y = [] # for elm in elements: # for i in range(3): # if elm.nodes[i].id in problem_ids: # problem_x.append(elm.x[i]) # problem_y.append(elm.y[i]) # problem_ids.remove(elm.nodes[i].id) # ax.plot(problem_x, problem_y, 'or') if save: fig.savefig(fig_name) else: fig.show()
def showStitchedModels(mods, axes=None, cmin=None, cmax=None, **kwargs): """ Show several 1d block models as (stitched) section. """ x = kwargs.pop('x', np.arange(len(mods))) topo = kwargs.pop('topo', x*0) nlay = int(np.floor((len(mods[0]) - 1) / 2.)) + 1 if cmin is None or cmax is None: cmin = 1e9 cmax = 1e-9 for model in mods: res = np.asarray(model)[nlay - 1:nlay * 2 - 1] cmin = min(cmin, min(res)) cmax = max(cmax, max(res)) if kwargs.pop('sameSize', True): # all having the same width dx = np.ones_like(x)*np.median(np.diff(x)) else: dx = np.diff(x) * 1.05 dx = np.hstack((dx, dx[-1])) x1 = x - dx / 2 if axes is None: fig, ax = plt.subplots() else: ax = axes fig = ax.figure # ax.plot(x, x * 0., 'k.') zm = kwargs.pop('zm', None) maxz = 0. if zm is not None: maxz = zm recs = [] RES = [] for i, mod in enumerate(mods): mod1 = np.asarray(mod) res = mod1[nlay - 1:] RES.extend(res) thk = mod1[:nlay - 1] thk = np.hstack((thk, thk[-1])) z = np.hstack((0., np.cumsum(thk))) if zm is not None: thk[-1] = zm - z[-2] z[-1] = zm else: maxz = max(maxz, z[-1]) for j in range(len(thk)): recs.append(Rectangle((x1[i], topo[i]-z[j]), dx[i], -thk[j])) pp = PatchCollection(recs, edgecolors=kwargs.pop('edgecolors', 'none')) pp.set_edgecolor(kwargs.pop('edgecolors', 'none')) pp.set_linewidths(0.0) ax.add_collection(pp) if 'cmap' in kwargs: pp.set_cmap(kwargs['cmap']) print(cmin, cmax) norm = LogNorm(cmin, cmax) pp.set_norm(norm) pp.set_array(np.array(RES)) # pp.set_clim(cmin, cmax) ax.set_ylim((-maxz, max(topo))) ax.set_xlim((x1[0], x1[-1] + dx[-1])) cbar = None if kwargs.pop('colorBar', True): cbar = plt.colorbar(pp, ax=ax, norm=norm, orientation='horizontal', aspect=60) # , ticks=[1, 3, 10, 30, 100, 300]) if 'ticks' in kwargs: cbar.set_ticks(kwargs['ticks']) # cbar.autoscale_None() if axes is None: # newly created fig+ax return fig, ax else: # already given, better give back color bar return cbar
def ismr_map (mesh_path, log_path, save=False, fig_name=None): # Limits on longitude and latitude for each ice shelf # These depend on the source geometry, in this case RTopo 1.05 # Note there is one extra index at the end of each array; this is because # the Ross region crosses the line 180W and therefore is split into two # We have -181 and 181 not -180 and 180 at this boundary so that # elements which cross the boundary are still counted lon_min = [-62.67, -65.5, -79.17, -85, -104.17, -102.5, -108.33, -114.5, -135.67, -149.17, -155, 144, 115, 94.17, 80.83, 65, 33.83, 19, 12.9, 9.33, -10.05, -28.33, -181, 158.33] lon_max = [-59.33, -60, -66.67, -28.33, -88.83, -99.17, -103.33, -111.5, -114.33, -140, -145, 146.62, 123.33, 102.5, 89.17, 75, 37.67, 33.33, 16.17, 12.88, 7.6, -10.33, -146.67, 181] lat_min = [-73.03, -69.35, -74.17, -83.5, -73.28, -75.5, -75.5, -75.33, -74.9, -76.42, -78, -67.83, -67.17, -66.67, -67.83, -73.67, -69.83, -71.67, -70.5, -70.75, -71.83, -76.33, -85, -84.5] lat_max = [-69.37, -66.13, -69.5, -74.67, -71.67, -74.17, -74.67, -73.67, -73, -75.17, -76.41, -66.67, -66.5, -64.83, -66.17, -68.33, -68.67, -68.33, -69.33, -69.83, -69.33, -71.5, -77.77, -77] # Area of each ice shelf in m^2 (printed to screen during # timeseries_massloss.py, update if the mesh changes) area = [9410595961.42, 48147893361.6, 46287951910.9, 429798928470.0, 27030080949.7, 3839594948.81, 2499220358.3, 3908582947.28, 29823059449.5, 4268520899.01, 11108310834.3, 3102730054.84, 4632897701.36, 26030138936.9, 11651566872.8, 64322690314.0, 2957848286.81, 40563562257.6, 6778604330.34, 5671169444.22, 52720412012.5, 72401508276.4, 475666675975.0] # Observed melt rate (Rignot 2013) and uncertainty for each ice shelf, in Gt/y obs_ismr = [0.1, 0.4, 3.1, 0.3, 1.7, 16.2, 17.7, 7.8, 4.3, 0.6, 1.5, 1.4, 7.7, 2.8, 1.7, 0.6, -0.4, 0.4, 0.7, 0.5, 0.5, 0.1, 0.1] obs_ismr_error = [0.6, 1, 0.8, 0.1, 0.6, 1, 1, 0.6, 0.4, 0.3, 0.3, 0.6, 0.7, 0.6, 0.7, 0.4, 0.6, 0.4, 0.2, 0.2, 0.2, 0.2, 0.1] # Density of ice in kg/m^3 rho_ice = 916 # Plotting parameters max_lat_plot = -63+90 mask_cavities = True circumpolar = True # Assume timeseries are 5-day averages days_per_output = 5 output_per_year = 365.0/days_per_output # Build FESOM mesh # Get separate patches for the open ocean elements so we can mask them out elements, mask_patches = make_patches(mesh_path, circumpolar, mask_cavities) patches = iceshelf_mask(elements) # Read log file f = open(log_path, 'r') # Skip the first line (header) f.readline() # Count the number of time indices for the first variable (total mass loss # for all ice shelves, which we don't care about) num_time = 0 for line in f: try: tmp = float(line) num_time += 1 except(ValueError): # Reached header for first individual ice shelf break # Set up array for melt rate values at each ice shelf ismr_ts = empty([len(obs_ismr), num_time]) index = 0 # Loop over ice shelves while index < len(obs_ismr): t = 0 for line in f: try: # Convert from mass loss to area-averaged melt rate ismr_ts[index,t] = float(line)*1e12/(rho_ice*area[index]) t += 1 except(ValueError): # Reached the header for the next ice shelf break index += 1 # Find unexplained error in annual average ismr = empty(len(obs_ismr)) error_vals = empty(len(obs_ismr)) for index in range(len(obs_ismr)): # Calculate annual average ismr[index] = mean(ismr_ts[index, -output_per_year:]) # Calculate range of observations ismr_low = obs_ismr[index] - obs_ismr_error[index] ismr_high = obs_ismr[index] + obs_ismr_error[index] # Calculate unexplained percent error in melt rate if ismr[index] < ismr_low: # Simulated melt rate too low error_vals[index] = (ismr[index] - ismr_low)/ismr_low*100 elif ismr[index] > ismr_high: # Simulated melt rate too high error_vals[index] = (ismr[index] - ismr_high)/ismr_high*100 else: # Simulated melt rate within observational error estimates error_vals[index] = 0 # Scale for plotting max_val = 100 #amax(abs(error_vals)) # Build a field of ice shelf melt rate unexplained percent error values = [] # Keep track of which elements are in ice shelves we care about location_flag = zeros(len(elements)) for i in range(len(elements)): elm = elements[i] # Make sure we're actually in an ice shelf cavity if elm.cavity: error_tmp = 0.0 # Loop over ice shelves for index in range(len(obs_ismr)): # Figure out whether or not this element is part of the given # ice shelf if all(elm.lon >= lon_min[index]) and all(elm.lon <= lon_max[index]) and all(elm.lat >= lat_min[index]) and all(elm.lat <= lat_max[index]): location_flag[i] = 1 error_tmp = error_vals[index] if index == len(obs_ismr)-1: # Ross region is split in two if all(elm.lon >= lon_min[index+1]) and all(elm.lon <= lon_max[index+1]) and all(elm.lat >= lat_min[index+1]) and all(elm.lat <= lat_max[index+1]): location_flag[i] = 1 error_tmp = error_vals[index] values.append(error_tmp) # Set up a grey square covering the domain, anything that isn't covered # up later is land x_reg, y_reg = meshgrid(linspace(-lat_max, lat_max, num=100), linspace(-lat_max, lat_max, num=100)) land_square = zeros(shape(x_reg)) # Plot fig = figure(figsize=(16,12)) ax = fig.add_subplot(1,1,1,aspect='equal') # Start with grey square background for land contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(patches, cmap='RdBu_r') img.set_array(array(values)) img.set_edgecolor('face') img.set_clim(-max_val, max_val) ax.add_collection(img) # Mask out the open ocean in white overlay = PatchCollection(mask_patches, facecolor=(1,1,1)) overlay.set_edgecolor('face') ax.add_collection(overlay) # Contour ice shelf front contour_lines = [] for elm in elements: # Select elements where exactly 2 of the 3 nodes are in a cavity if count_nonzero(elm.cavity_nodes) == 2: # Save the coastal flags and x- and y- coordinates of these 2 coast_tmp = [] x_tmp = [] y_tmp = [] for i in range(3): if elm.cavity_nodes[i]: coast_tmp.append(elm.coast_nodes[i]) x_tmp.append(elm.x[i]) y_tmp.append(elm.y[i]) # Select elements where at most 1 of these 2 nodes are coastal if count_nonzero(coast_tmp) < 2: # Draw a line between the 2 nodes contour_lines.append([(x_tmp[0], y_tmp[0]), (x_tmp[1], y_tmp[1])]) # Add all the lines to the plot contours = LineCollection(contour_lines, edgecolor='black', linewidth=1) ax.add_collection(contours) # Configure plot xlim([-max_lat_plot, max_lat_plot]) ylim([-max_lat_plot, max_lat_plot]) axis('off') title('Bias in Ice Shelf Melt Rate (%)', fontsize=30) cbar = colorbar(img) cbar.ax.tick_params(labelsize=20) # Finished if save: fig.savefig(fig_name) else: fig.show()
def patchValMap(vals, xvec=None, yvec=None, ax=None, cMin=None, cMax=None, logScale=None, label=None, dx=1, dy=None, **kwargs): """ plot previously generated (generateVecMatrix) y map (category) Parameters ---------- A : iterable to show xvec : dict {i:num} dict (must match A.shape[0]) ymap : iterable vector for x axis (must match A.shape[0]) ax : mpl.axis axis to plot, if not given a new figure is created cMin/cMax : float minimum/maximum color values logScale : bool logarithmic colour scale [min(A)>0] label : string colorbar label """ if cMin is None: cMin = np.min(vals) if cMax is None: cMax = np.max(vals) if logScale is None: logScale = (cMin > 0.0) if logScale: norm = LogNorm(vmin=cMin, vmax=cMax) else: norm = Normalize(vmin=cMin, vmax=cMax) if 'ax' is None: fig, ax = plt.subplots() recs = [] if dy is None: # map y values to unique ymap = {xy: ii for ii, xy in enumerate(np.unique(yvec))} for i in range(len(vals)): recs.append(Rectangle((xvec[i]-dx/2, ymap[yvec[i]]-0.5), dx, 1)) else: for i in range(len(vals)): recs.append(Rectangle((xvec[i]-dx/2, yvec[i]-dy/2), dx, dy)) pp = PatchCollection(recs) col = ax.add_collection(pp) pp.set_edgecolor(None) pp.set_linewidths(0.0) if 'cmap' in kwargs: pp.set_cmap(kwargs.pop('cmap')) pp.set_norm(norm) pp.set_array(np.array(vals)) pp.set_clim(cMin, cMax) ax.set_xlim(min(xvec)-dx/2, max(xvec)+dx/2) ax.set_ylim(len(ymap)-0.5, -0.5) updateAxes_(ax) cbar = None if kwargs.pop('colorBar', True): cbar = pg.mplviewer.createColorbar(col, cMin=cMin, cMax=cMax, nLevs=5, label=label) return ax, cbar, ymap
def patchValMap(vals, xvec=None, yvec=None, ax=None, cMin=None, cMax=None, logScale=None, label=None, dx=1, dy=None, **kwargs): """Plot previously generated (generateVecMatrix) y map (category). Parameters ---------- vals : iterable Data values to show. xvec : dict {i:num} dict (must match vals.shape[0]) ymap : iterable vector for x axis (must match vals.shape[0]) ax : mpl.axis axis to plot, if not given a new figure is created cMin/cMax : float minimum/maximum color values logScale : bool logarithmic colour scale [min(vals)>0] label : string colorbar label ** kwargs: * circular : bool Plot in polar coordinates. """ if cMin is None: cMin = np.min(vals) if cMax is None: cMax = np.max(vals) if logScale is None: logScale = (cMin > 0.0) norm = None if logScale and cMin > 0: norm = LogNorm(vmin=cMin, vmax=cMax) else: norm = Normalize(vmin=cMin, vmax=cMax) if ax is None: ax = plt.subplots()[1] recs = [] circular = kwargs.pop('circular', False) if circular: recs = [None] * len(xvec) if dy is None: # map y values to unique ymap = {xy: ii for ii, xy in enumerate(np.unique(yvec))} xyMap = {} for i, y in enumerate(yvec): if y not in xyMap: xyMap[y] = [] xyMap[y].append(i) # maxR = max(ymap.values()) # what's that for? not used dR = 1 / (len(ymap.values())+1) # dOff = np.pi / 2 # what's that for? not used for y, xIds in xyMap.items(): r = 1. - dR*(ymap[y]+1) # ax.plot(r * np.cos(xvec[xIds]), # r * np.sin(xvec[xIds]), 'o') # print(y, ymap[y]) for i in xIds: phi = xvec[i] # x = r * np.cos(phi) # what's that for? not used y = r * np.sin(phi) dPhi = (xvec[1] - xvec[0]) recs[i] = Wedge((0., 0.), r + dR/1.5, (phi - dPhi)*360/(2*np.pi), (phi + dPhi)*360/(2*np.pi), width=dR, zorder=1+r) # if i < 5: # ax.text(x, y, str(i)) # pg.wait() else: raise("Implementme") else: if dy is None: # map y values to unique ymap = {xy: ii for ii, xy in enumerate(np.unique(yvec))} for i in range(len(vals)): recs.append(Rectangle((xvec[i] - dx / 2, ymap[yvec[i]] - 0.5), dx, 1)) else: for i in range(len(vals)): recs.append(Rectangle((xvec[i] - dx / 2, yvec[i] - dy / 2), dx, dy)) ax.set_xlim(min(xvec) - dx / 2, max(xvec) + dx / 2) ax.set_ylim(len(ymap) - 0.5, -0.5) pp = PatchCollection(recs) # ax.clear() col = ax.add_collection(pp) pp.set_edgecolor(None) pp.set_linewidths(0.0) if circular: pp.set_edgecolor('black') pp.set_linewidths(0.1) cmap = pg.mplviewer.cmapFromName(**kwargs) if kwargs.pop('markOutside', False): cmap.set_bad('grey') cmap.set_under('darkgrey') cmap.set_over('lightgrey') cmap.set_bad('black') pp.set_cmap(cmap) pp.set_norm(norm) pp.set_array(vals) pp.set_clim(cMin, cMax) updateAxes_(ax) cbar = kwargs.pop('colorBar', True) ori = kwargs.pop('orientation', 'horizontal') if cbar in ['horizontal', 'vertical']: ori = cbar cbar = True if cbar is True: # not for cbar=1, which is really confusing! cbar = pg.mplviewer.createColorBar(col, cMin=cMin, cMax=cMax, nLevs=5, label=label, orientation=ori) elif cbar is not False: # .. cbar is an already existing cbar .. so we update its values pg.mplviewer.updateColorBar(cbar, cMin=cMin, cMax=cMax, nLevs=5, label=label) updateAxes_(ax) return ax, cbar, ymap
def nsidc_aice_seasonal (mesh_path, file_path1, file_path2, save=False, fig_name=None): # FESOM parameters circumpolar=True mask_cavities=True # Season names for plot titles season_names = ['DJF', 'MAM', 'JJA', 'SON'] # NSIDC file paths nsidc_head = '/short/m68/kaa561/nsidc_aice/seaice_conc_monthly_sh' nsidc_head_0 = nsidc_head + '_f11_' nsidc_head_1 = nsidc_head + '_f13_' nsidc_tail = '_v02r00.nc' # Degrees to radians conversion factor deg2rad = pi/180.0 # Number of days per month (just for CICE) ndays_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # Build FESOM mesh elements, patches = make_patches(mesh_path, circumpolar, mask_cavities) # Get seasonal averages of the FESOM output # This is hard-coded and ugly id = Dataset(file_path1, 'r') n2d = id.variables['area'].shape[1] fesom_data = zeros([4, n2d]) # DJF: 1/5 of index 67 (1-based) and indices 68-73 in file1; indices 1-11 # and 4/5 of index 12 in file2; 90 days in total fesom_data[0,:] = id.variables['area'][66,:] + sum(id.variables['area'][67:73,:]*5, axis=0) id.close() id = Dataset(file_path2, 'r') fesom_data[0,:] += sum(id.variables['area'][0:11,:]*5, axis=0) + id.variables['area'][11,:]*4 fesom_data[0,:] /= 90 # MAM: 1/5 of index 12, indices 13-30, and 1/5 of index 31 in file2; # 92 days in total fesom_data[1,:] = id.variables['area'][11,:] + sum(id.variables['area'][12:30,:]*5, axis=0) + id.variables['area'][30,:] fesom_data[1,:] /= 92 # JJA: 4/5 of index 31, indices 32-48, and 3/5 of index 49 in file2; # 92 days in total fesom_data[2,:] = id.variables['area'][30,:]*4 + sum(id.variables['area'][31:48]*5, axis=0) + id.variables['area'][48,:]*3 fesom_data[2,:] /= 92 # SON: 2/5 of index 49, indices 50-66, and 4/5 of index 67 in file2; # 91 days in total fesom_data[3,:] = id.variables['area'][48,:]*2 + sum(id.variables['area'][49:66,:]*5, axis=0) + id.variables['area'][66,:]*4 fesom_data[3,:] /= 91 id.close() # Read NSIDC grid from the January file id = Dataset(nsidc_head_0 + '199501' + nsidc_tail, 'r') nsidc_lon = id.variables['longitude'][:,:] nsidc_lat = id.variables['latitude'][:,:] id.close() # Initialise seasonal averages of NSIDC data nsidc_data = ma.empty([4, size(nsidc_lon,0), size(nsidc_lon,1)]) nsidc_data[:,:] = 0.0 # Process one season at a time for season in range(4): # Figure out which months we care about if season == 0: # DJF nsidc_months = [12, 1, 2] elif season == 1: # MAM nsidc_months = [3, 4, 5] elif season == 2: # JJA nsidc_months = [6, 7, 8] elif season == 3: # SON nsidc_months = [9, 10, 11] season_days = 0 # Number of days in season; this will be incremented # Process one month at a time for month in nsidc_months: # Construct NSIDC file path if month < 10: nsidc_file = nsidc_head_0 + '19950' + str(month) + nsidc_tail else: nsidc_file = nsidc_head_1 + '1995' + str(month) + nsidc_tail # Read concentration data id = Dataset(nsidc_file, 'r') nsidc_data_raw = id.variables['seaice_conc_monthly_cdr'][0,:,:] # Read std just for the mask nsidc_mask = id.variables['stdev_of_seaice_conc_monthly_cdr'][0,:,:] id.close() # Set land mask nsidc_data_tmp = ma.empty(shape(nsidc_data_raw)) nsidc_data_tmp[:,:] = 0.0 nsidc_data_tmp[~nsidc_mask.mask] = nsidc_data_raw[~nsidc_mask.mask] nsidc_data_tmp[nsidc_mask.mask] = ma.masked # Accumulate master array, weighted with number of days per month nsidc_data[season,:,:] += nsidc_data_tmp*ndays_month[month-1] season_days += ndays_month[month-1] # Convert from sum to average nsidc_data[season,:,:] /= season_days # Convert to spherical coordinates nsidc_x = -(nsidc_lat+90)*cos(nsidc_lon*deg2rad+pi/2) nsidc_y = (nsidc_lat+90)*sin(nsidc_lon*deg2rad+pi/2) # Find boundaries for each side of plot based on extent of NSIDC grid bdry1 = amax(nsidc_x[:,0]) bdry2 = amin(nsidc_x[:,-1]) bdry3 = amin(nsidc_y[:,0]) bdry4 = amax(nsidc_y[:,-1]) # Set consistent colour levels lev = linspace(0, 1, num=50) # Plot fig = figure(figsize=(20,9)) # Loop over seasons for season in range(4): # NSIDC ax = fig.add_subplot(2, 4, season+1, aspect='equal') contourf(nsidc_x, nsidc_y, nsidc_data[season,:,:], lev) if season == 0: text(-39, 0, 'NSIDC', fontsize=24, ha='right') title(season_names[season], fontsize=24) xlim([bdry1, bdry2]) ylim([bdry3, bdry4]) axis('off') # Build an array of FESOM data values corresponding to each Element values = [] for elm in elements: # For each element not in an ice shelf cavity, append the mean # value for the 3 component Nodes if not elm.cavity: values.append(mean([fesom_data[season,elm.nodes[0].id], fesom_data[season,elm.nodes[1].id], fesom_data[season,elm.nodes[2].id]])) # Plot FESOM data ax = fig.add_subplot(2, 4, season+5, aspect='equal') img = PatchCollection(patches, cmap=jet) img.set_array(array(values)) img.set_clim(vmin=0, vmax=1) img.set_edgecolor('face') ax.add_collection(img) xlim([bdry1, bdry2]) ylim([bdry3, bdry4]) axis('off') if season == 0: text(-39, 0, 'FESOM', fontsize=24, ha='right') # Add a horizontal colorbar at the bottom cbaxes = fig.add_axes([0.25, 0.04, 0.5, 0.02]) cbar = colorbar(img, orientation='horizontal', ticks=arange(0,1+0.25,0.25), cax=cbaxes) cbar.ax.tick_params(labelsize=16) # Add the main title suptitle('Sea ice concentration', fontsize=30) # Decrease space between plots subplots_adjust(wspace=0.025,hspace=0.025) # Finished if save: fig.savefig(fig_name) else: fig.show()
chrom_set.add(segSeqD[i[0]][0]) # for i in range(1,24): # chrom_set.add("chr" + str(i)) sorted_chrom = sorted(chrom_set,key=lambda x:int(x.rsplit("chr")[-1])) sorted_chrom_colors = [chromosome_colors[x] for x in sorted_chrom] legend_patches = [] for chrom,color in zip(sorted_chrom,sorted_chrom_colors): legend_patches.append(mpatches.Patch(color=color,label=chrom)) plt.legend(handles=legend_patches,fontsize=8,loc=3,bbox_to_anchor=(-.3,.15)) p = PatchCollection(patches) p.set_facecolor(f_color_v) p.set_edgecolor(e_color_v) p.set_linewidth(lw_v) ax.add_collection(p) ax.set_aspect(1.0) plt.axis('off') plt.savefig(fname + '.png',dpi=600) plt.savefig(fname + '.pdf',format='pdf') plt.close() print "done plotting bionano" #handles basic (non-bionano case) if args.feature_labels: #make a separate figure plt.clf() fig, ax = plt.subplots()
class ArrayDisplay: """ Display a top-town view of a telescope array """ def __init__(self, telx, tely, tel_type=None, radius=20, axes=None, title="Array", autoupdate=True): if tel_type is None: tel_type = np.ones(len(telx)) patches = [Rectangle(xy=(x-radius/2, y-radius/2), width=radius, height=radius, fill=False) for x, y in zip(telx, tely)] self.autoupdate = autoupdate self.telescopes = PatchCollection(patches, match_original=True) self.telescopes.set_clim(1, 9) rgb = matplotlib.cm.Set1((tel_type-1)/9) self.telescopes.set_edgecolor(rgb) self.telescopes.set_linewidth(2.0) self.axes = axes if axes is not None else plt.gca() self.axes.add_collection(self.telescopes) self.axes.set_aspect(1.0) self.axes.set_title(title) self.axes.set_xlim(-1000, 1000) self.axes.set_ylim(-1000, 1000) self.axes_hillas = axes if axes is not None else plt.gca() @property def values(self): """An array containing a value per telescope""" return self.telescopes.get_array() @values.setter def values(self, values): """ set the telescope colors to display """ self.telescopes.set_array(values) self._update() def _update(self): """ signal a redraw if necessary """ if self.autoupdate: plt.draw() def add_ellipse(self, centroid, length, width, angle, **kwargs): """ plot an ellipse on top of the camera Parameters ---------- centroid: (float, float) position of centroid length: float major axis width: float minor axis angle: float rotation angle wrt x-axis about the centroid, anticlockwise, in radians asymmetry: float 3rd-order moment for directionality if known kwargs: any MatPlotLib style arguments to pass to the Ellipse patch """ ellipse = Ellipse(xy=centroid, width=length, height=width, angle=np.degrees(angle), fill=True, **kwargs) self.axes.add_patch(ellipse) return ellipse def add_polygon(self, centroid, radius, nsides=3, **kwargs): """ plot a polygon on top of the camera Parameters ---------- centroid: (float, float) position of centroid radius: float radius nsides: int Number of points on polygon kwargs: any MatPlotLib style arguments to pass to the RegularPolygon patch """ polygon = RegularPolygon(xy=centroid, radius=radius, numVertices=nsides, **kwargs) self.axes.add_patch(polygon) return polygon def overlay_moments(self, momparams, tel_position, scale_fac, **kwargs): """helper to overlay ellipse from a `reco.MomentParameters` structure Parameters ---------- momparams: `reco.MomentParameters` structuring containing Hillas-style parameterization tel_position: list (x, y) positions of each telescope scale_fac: float scaling factor to apply to width and length when overlaying moments kwargs: key=value any style keywords to pass to matplotlib (e.g. color='red' or linewidth=6) """ # strip off any units ellipse_list = list() size_list = list() i = 0 for h in momparams: length = u.Quantity(momparams[h].length).value * scale_fac width = u.Quantity(momparams[h].width).value * scale_fac size_list.append(u.Quantity(momparams[h].size).value) tel_x = u.Quantity(tel_position[0][i]).value tel_y = u.Quantity(tel_position[1][i]).value i += 1 ellipse = Ellipse(xy=(tel_x,tel_y), width=length, height=width, angle=np.degrees(momparams[h].psi.rad)) ellipse_list.append(ellipse) patches = PatchCollection(ellipse_list, **kwargs) patches.set_clim(0, 1000) # Set ellipse colour based on image size patches.set_array(np.asarray(size_list)) self.axes_hillas.add_collection(patches) def overlay_axis(self, momparams, tel_position, **kwargs): """helper to overlay ellipse from a `reco.MomentParameters` structure Parameters ---------- momparams: `reco.MomentParameters` structuring containing Hillas-style parameterization tel_position: list (x, y) positions of each telescope kwargs: key=value any style keywords to pass to matplotlib (e.g. color='red' or linewidth=6) """ # strip off any units i = 0 for h in momparams: tel_x = u.Quantity(tel_position[0][i]).value tel_y = u.Quantity(tel_position[1][i]).value psi = u.Quantity(momparams[h].psi).value x_sc = [tel_x - np.cos(psi) * 10000, tel_x + np.cos(psi) * 10000] y_sc = [tel_y - np.sin(psi) * 10000, tel_y + np.sin(psi) * 10000] i += 1 self.axes_hillas.add_line(Line2D(x_sc, y_sc, linestyle='dashed', color='black'))
colors = [] if dimension == 1: for i in range(hcuts): patches += [ Wedge(origin, radius, 360.0/2/2/(hcuts-1)*(2*i-1), 360.0/2/2/(hcuts-1)*(2*i+1), width=width) ] #TODO colors += [i%5] elif dimension == 2: for i in range(hcuts): patches += [ Wedge(origin, radius, 360.0/hcuts*i, 360.0/hcuts*(i+1), width=width) ] #TODO colors += [i%5] else: #TODO pass collection = PatchCollection(patches, cmap = cm.jet) collection.set_array(np.array(colors)) collection.set_edgecolor('none') fig, ax = plt.subplots() ax.add_collection(collection) plt.colorbar(collection) plt.xlim(-1,1) plt.ylim(-1,1) plt.show() file.close()
def plot_wct (mesh_path, fig_name): # Plotting parameters circumpolar = True lat_max = -30 + 90 font_sizes = [240, 192, 160] # Build triangular patches for each element elements, patches = make_patches(mesh_path, circumpolar) # Read the ice shelf draft for each node file = open(mesh_path + 'shelf.out', 'r') node_shelf = [] for line in file: node_shelf.append(-float(line)) file.close() # Read the depth for each node file = open(mesh_path + 'depth.out', 'r') node_depth = [] for line in file: node_depth.append(-float(line)) file.close() # Calculate water column thickness node_wct = abs(array(node_depth)) - abs(array(node_shelf)) # For each element, calculate the minimum wct of the 3 component nodes elm_wct = [] for elm in elements: wct1 = node_wct[(elm.nodes[0]).id-1] wct2 = node_wct[(elm.nodes[1]).id-1] wct3 = node_wct[(elm.nodes[2]).id-1] elm_wct.append(amin(array([wct1, wct2, wct3]))) # Set up figure fig = figure(figsize=(128, 96)) ax = fig.add_subplot(1,1,1, aspect='equal') # Set colours for patches and add them to plot img = PatchCollection(patches, cmap=jet) img.set_array(array(elm_wct)) img.set_edgecolor('face') ax.add_collection(img) # Configure plot xlim([-lat_max, lat_max]) ylim([-lat_max, lat_max]) ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_ticks([]) title('Water column thickness (m)', fontsize=font_sizes[0]) cbar = colorbar(img) cbar.ax.tick_params(labelsize=font_sizes[2]) axis('off') # Plot specified points #problem_ids = [291, 297] #problem_x = [] #problem_y = [] #for elm in elements: #for i in range(3): #if elm.nodes[i].id in problem_ids: #problem_x.append(elm.x[i]) #problem_y.append(elm.y[i]) #problem_ids.remove(elm.nodes[i].id) #ax.plot(problem_x, problem_y, 'or') savefig(fig_name)
def patchMatrix(A, xmap=None, ymap=None, ax=None, cMin=None, cMax=None, logScale=None, label=None, dx=1, **kwargs): """ plot previously generated (generateVecMatrix) matrix Parameters ---------- A : numpy.array2d matrix to show xmap : dict {i:num} dict (must match A.shape[0]) ymap : iterable vector for x axis (must match A.shape[0]) ax : mpl.axis axis to plot, if not given a new figure is created cMin/cMax : float minimum/maximum color values logScale : bool logarithmic colour scale [min(A)>0] label : string colorbar label """ mat = np.ma.masked_where(A == 0.0, A, False) if cMin is None: cMin = np.min(mat) if cMax is None: cMax = np.max(mat) if logScale is None: logScale = (cMin > 0.0) if logScale: norm = LogNorm(vmin=cMin, vmax=cMax) else: norm = Normalize(vmin=cMin, vmax=cMax) if 'ax' is None: fig, ax = plt.subplots() iy, ix = np.nonzero(A) # != 0) recs = [] vals = [] for i in range(len(ix)): recs.append(Rectangle((ix[i]-dx/2, iy[i]-0.5), dx, 1)) vals.append(A[iy[i], ix[i]]) pp = PatchCollection(recs) col = ax.add_collection(pp) pp.set_edgecolor(None) pp.set_linewidths(0.0) if 'cmap' in kwargs: pp.set_cmap(kwargs.pop('cmap')) pp.set_norm(norm) pp.set_array(np.array(vals)) pp.set_clim(cMin, cMax) xval = [k for k in xmap.keys()] ax.set_xlim(min(xval)-dx/2, max(xval)+dx/2) ax.set_ylim(len(ymap)+0.5, -0.5) updateAxes_(ax) cbar = None if kwargs.pop('colorBar', True): cbar = pg.mplviewer.createColorbar(col, cMin=cMin, cMax=cMax, nLevs=5, label=label) return ax, cbar
y = pontos[:,1][t_i][0] # a cor do polígono vem da imagem original cores.append(image_rgb[y-1][x-1]) # criamos um polígono para representar o triângulo (aqui começa o desenho # que estamos sintetizando) poly = Polygon(pontos[:,[0,1]][t_i], True) patches.append(poly) # adicionamos os polígonos a uma coleção de colagens p = PatchCollection(patches) #print 'patches:', len(patches), 'regions:', len(cores) # definimos as cores conforme imagem original e as bordas em transparente p.set_facecolor(cores) p.set_edgecolor(cores) p.set_alpha(.8) # plotamos o desenho sintetizado ax3.add_collection(p) for ax in axes: ax.axis('off') nome_pintura = '%s_passos.svg' % IMG[:-4] fig.savefig(nome_pintura) print 'pintura gerada em: %s' % nome_pintura # lista com coordenadas de cada triângulo # print 'coords. triângulos:', coords_tri # número de triângulos # print 'num. de triângulos:', len(coords_tri)
def aice_hi_seasonal(mesh_path, file_path1, file_path2, save=False, fig_name=None): # FESOM parameters circumpolar = True mask_cavities = True # Season names for plot titles season_names = ["DJF", "MAM", "JJA", "SON"] # Build FESOM mesh elements, patches = make_patches(mesh_path, circumpolar, mask_cavities) # Get seasonal averages of the FESOM output # This is hard-coded and ugly id = Dataset(file_path1, "r") n2d = id.variables["area"].shape[1] aice = zeros([4, n2d]) hi = zeros([4, n2d]) # DJF: 1/5 of index 67 (1-based) and indices 68-73 in file1; indices 1-11 # and 4/5 of index 12 in file2; 90 days in total aice[0, :] = id.variables["area"][66, :] + sum(id.variables["area"][67:73, :] * 5, axis=0) hi[0, :] = id.variables["hice"][66, :] + sum(id.variables["hice"][67:73, :] * 5, axis=0) id.close() id = Dataset(file_path2, "r") aice[0, :] += sum(id.variables["area"][0:11, :] * 5, axis=0) + id.variables["area"][11, :] * 4 aice[0, :] /= 90 hi[0, :] += sum(id.variables["hice"][0:11, :] * 5, axis=0) + id.variables["hice"][11, :] * 4 hi[0, :] /= 90 # MAM: 1/5 of index 12, indices 13-30, and 1/5 of index 31 in file2; # 92 days in total aice[1, :] = ( id.variables["area"][11, :] + sum(id.variables["area"][12:30, :] * 5, axis=0) + id.variables["area"][30, :] ) aice[1, :] /= 92 hi[1, :] = ( id.variables["hice"][11, :] + sum(id.variables["hice"][12:30, :] * 5, axis=0) + id.variables["hice"][30, :] ) hi[1, :] /= 92 # JJA: 4/5 of index 31, indices 32-48, and 3/5 of index 49 in file2; # 92 days in total aice[2, :] = ( id.variables["area"][30, :] * 4 + sum(id.variables["area"][31:48, :] * 5, axis=0) + id.variables["area"][48, :] * 3 ) aice[2, :] /= 92 hi[2, :] = ( id.variables["hice"][30, :] * 4 + sum(id.variables["hice"][31:48, :] * 5, axis=0) + id.variables["hice"][48, :] * 3 ) hi[2, :] /= 92 # SON: 2/5 of index 49, indices 50-66, and 4/5 of index 67 in file2; # 91 days in total aice[3, :] = ( id.variables["area"][48, :] * 2 + sum(id.variables["area"][49:66, :] * 5, axis=0) + id.variables["area"][66, :] * 4 ) aice[3, :] /= 91 hi[3, :] = ( id.variables["hice"][48, :] * 2 + sum(id.variables["hice"][49:66, :] * 5, axis=0) + id.variables["hice"][66, :] * 4 ) hi[3, :] /= 91 id.close() # Plot fig = figure(figsize=(20, 9)) # Loop over seasons for season in range(4): # aice # Build an array of FESOM data values corresponding to each Element values1 = [] for elm in elements: # For each element not in an ice shelf cavity, append the mean # value for the 3 component Nodes if not elm.cavity: values1.append( mean([aice[season, elm.nodes[0].id], aice[season, elm.nodes[1].id], aice[season, elm.nodes[2].id]]) ) ax = fig.add_subplot(2, 4, season + 1, aspect="equal") img = PatchCollection(patches, cmap=jet) img.set_array(array(values1)) img.set_clim(vmin=0, vmax=1) img.set_edgecolor("face") ax.add_collection(img) xlim([-35, 35]) ylim([-33, 37]) axis("off") if season == 0: text(-39, 0, "aice (%)", fontsize=21, ha="right") title(season_names[season], fontsize=24) if season == 3: cbaxes1 = fig.add_axes([0.92, 0.55, 0.01, 0.3]) cbar1 = colorbar(img, ticks=arange(0, 1 + 0.25, 0.25), cax=cbaxes1) cbar1.ax.tick_params(labelsize=16) # hi values2 = [] for elm in elements: # For each element not in an ice shelf cavity, append the mean # value for the 3 component Nodes if not elm.cavity: values2.append( mean([hi[season, elm.nodes[0].id], hi[season, elm.nodes[1].id], hi[season, elm.nodes[2].id]]) ) ax = fig.add_subplot(2, 4, season + 5, aspect="equal") img = PatchCollection(patches, cmap=jet) img.set_array(array(values2)) img.set_clim(vmin=0, vmax=1.5) img.set_edgecolor("face") ax.add_collection(img) xlim([-35, 35]) ylim([-33, 37]) axis("off") if season == 0: text(-39, 0, "hi (m)", fontsize=21, ha="right") if season == 3: cbaxes2 = fig.add_axes([0.92, 0.15, 0.01, 0.3]) cbar2 = colorbar(img, ticks=arange(0, 1.5 + 0.5, 0.5), cax=cbaxes2) cbar2.ax.tick_params(labelsize=16) # Decrease space between plots subplots_adjust(wspace=0.025, hspace=0.025) # Finished if save: fig.savefig(fig_name) else: fig.show()