def plotDens3d(featL, group="grp", y="y"): """plot a 3d histogram after groupby""" from mpl_toolkits.mplot3d import Axes3D from matplotlib.collections import PolyCollection norm = len(set(featL[group])) verts = [] xs, zs = [], [] xs = np.arange(0, 1, 0.025) j = 0 for i, g in featL.groupby([group]): ys = np.histogram(g[y], len(xs))[0] / g[y].sum() ys[0], ys[-1] = 0, 0 verts.append(list(zip(xs, ys))) j += 1 zs.append(j / norm) ys = np.array(ys) poly = PolyCollection(verts, facecolor=colorL[:j]) poly.set_edgecolor('black') fig = plt.figure() ax = fig.gca(projection='3d') ax.add_collection3d(poly, zs=zs, zdir='y') # ax.set_xlim3d(0, 10) # ax.set_ylim3d(0., .3) # plt.axis('off') ax.grid(False) ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([]) plt.grid(b=None) ax.set_zlim3d(0, .3)
def get_mesh_plot(fig, mesh, values=None, invert_y_axis=True): ax = fig.add_subplot(111) vertexIDs = mesh._orderedCellVertexIDs vertexCoords = mesh.vertexCoords xCoords = np.take(vertexCoords[0], vertexIDs) yCoords = np.take(vertexCoords[1], vertexIDs) polys = [] for x, y in zip(xCoords.swapaxes(0, 1), yCoords.swapaxes(0, 1)): if hasattr(x, 'mask'): x = x.compressed() if hasattr(y, 'mask'): y = y.compressed() polys.append(zip(x, y)) collection = PolyCollection(polys) collection.set_facecolors('None') collection.set_edgecolor((0.2, 0.2, 0.2, 0.5)) if invert_y_axis: ax.invert_yaxis() ax.add_collection(collection) if values: pass
def plot_prediction_over_epochs_plt(): """ Plots the polygon generated by generate_vertices() using matplotlib. """ generate_vertices() results_dir = '../results/UKDALE-RNN-lr=1e-5-2018-01-26 14:33:59' verts = pickle.load(open(os.path.join(results_dir, 'vertices.pkl'), 'rb')) zs = pickle.load(open(os.path.join(results_dir, 'zs.pkl'), 'rb')) ys = pickle.load(open(os.path.join(results_dir, 'ys.pkl'), 'rb')) fig = plt.figure(figsize=(18, 8)) ax = fig.gca(projection='3d') poly = PolyCollection(verts[::], facecolors='w') poly.set_edgecolor((0, 0, 0, .5)) poly.set_facecolor((.9, .9, 1, 0.3)) ax.add_collection3d(poly, zs=zs[::], zdir='y') ax.set_xlabel('timestamps') ax.set_xlim3d(0, ys.shape[0]) ax.set_ylabel('epochs') ax.set_ylim3d(0, 320) ax.set_zlabel('power') ax.set_zlim3d(0, 2000) ax.view_init(-40, -94) plt.savefig(os.path.join(results_dir, 'prediction_over_epochs.png'))
def plotHealpixPolygons(ax, projection, vertices, color=None, vmin=None, vmax=None, **kwargs): """Plot Healpix cell polygons onto map. Args: ax: matplotlib axes projection: map projection vertices: Healpix cell boundaries in RA/Dec, from getCountAtLocations() color: string or matplib color, or numeric array to set polygon colors vmin: if color is numeric array, use vmin to set color of minimum vmax: if color is numeric array, use vmin to set color of minimum **kwargs: matplotlib.collections.PolyCollection keywords Returns: matplotlib.collections.PolyCollection """ from matplotlib.collections import PolyCollection vertices_ = np.empty_like(vertices) vertices_[:, :, 0], vertices_[:, :, 1] = projection(vertices[:, :, 0], vertices[:, :, 1]) coll = PolyCollection(vertices_, array=color, **kwargs) coll.set_clim(vmin=vmin, vmax=vmax) coll.set_edgecolor("face") ax.add_collection(coll) return coll
def plot_grid_2d(g, cell_value, ax, **kwargs): """ Plot the 2d grid g to the axis ax, with cell_value represented by the cell coloring. keywargs: Keyword arguments: color_map: Limits of the cell value color axis. linewidth: Width of faces in 2d and edges in 3d. rgb: Color map weights. Defaults to [1, 0, 0]. alpha: Transparency of the plot. cells: boolean array with length number of cells. Only plot cells c where cells[c]=True """ faces, _, _ = sps.find(g.cell_faces) nodes, _, _ = sps.find(g.face_nodes) alpha = kwargs.get("alpha", 1) if kwargs.get("color_map"): scalar_map = kwargs["color_map"] @pp.time_logger(sections=module_sections) def color_face(value): return scalar_map.to_rgba(value, alpha) else: cell_value = np.zeros(g.num_cells) rgb = kwargs.get("rgb", [1, 0, 0]) @pp.time_logger(sections=module_sections) def color_face(value): return np.r_[rgb, alpha] cells = kwargs.get("cells", np.ones(g.num_cells, dtype=bool)) for c in np.arange(g.num_cells): if not cells[c]: continue loc_f = slice(g.cell_faces.indptr[c], g.cell_faces.indptr[c + 1]) faces_loc = faces[loc_f] loc_n = g.face_nodes.indptr[faces_loc] pts_pairs = np.array([nodes[loc_n], nodes[loc_n + 1]]) sorted_nodes, _ = pp.utils.sort_points.sort_point_pairs(pts_pairs) ordering = sorted_nodes[0, :] pts = g.nodes[:, ordering] linewidth = kwargs.get("linewidth", 1) if kwargs.get("plot_2d", False): poly = PolyCollection([pts[:2].T], linewidth=linewidth) poly.set_edgecolor("k") poly.set_facecolor(color_face(cell_value[c])) ax.add_collection(poly) else: poly = Poly3DCollection([pts.T], linewidth=linewidth) poly.set_edgecolor("k") poly.set_facecolors(color_face(cell_value[c])) ax.add_collection3d(poly) if not kwargs.get("plot_2d", False): ax.view_init(90, -90)
def state_est(alg, real_x, name="", **kwargs): """ TODO: [v] Using kwargs to involve more plotting parameters, for providing a way to specify the xmax manually. 2. Display the bias between real states and the mode estimates or weighted average estimates of them, as a series plot verus the time index. Keywords arguments: xmin, xmax: range of states' values studied, default value is -5, 5 Do the filtering step by step with the alg object, and draw the waterfall plot to illustrate the distribution of estimated states at selected time index. From the waterfall plot we may assess the accuracy of estimation. """ T = len(alg.fk.data) fig = plt.figure(figsize=(10, 5)) ax = fig.gca(projection='3d') xmin, xmax = kwargs.get("xmin", -5), kwargs.get("xmax", 5) xs = np.arange(xmin, xmax, 0.1) verts = [] ts = np.arange(0, T, 10) hrx = [] for i in range(T): next(alg) if i % 10 == 0: dens = sm.nonparametric.KDEUnivariate(alg.X) dens.fit() ds = dens.evaluate(xs) ds[0], ds[-1] = 0, 0 verts.append(list(zip(xs, ds))) hrx.append(dens.evaluate(real_x[i])) poly = PolyCollection(verts, facecolor=(1, 1, 1, 0.6)) # poly.set_alpha(0.7) poly.set_edgecolor((0, 0, 0, 1)) ax.add_collection3d(poly, zs=ts, zdir='y') ax.scatter([real_x[i] for i in ts], ts, hrx) ax.set( title=f"Waterfall representation of filtering distributions {name}", xlabel="State", ylabel="Time index", zlabel="Density", xlim3d=(xmin, xmax), ylim3d=(max(ts) + 1, min(ts) - 1), zlim3d=(0, 0.6), ) # ax.set_xlabel('State') # ax.set_xlim3d(xmin, xmax) # ax.set_ylabel('Time index') # ax.set_ylim3d(max(ts)+1,min(ts)-1) # ax.set_zlabel('Density') # ax.set_zlim3d(0, 0.6) # ax.set_title(f"Waterfall representation of filtering distributions {name}") ax.view_init(30, 60)
def plot_polys(verts, polys, facecolors=(1, 1, 1)): collection = PolyCollection([verts[p, ::-1] for p in polys]) collection.set_facecolor(facecolors) collection.set_edgecolor((0.8, 0.8, 0.8)) collection.set_linewidth(0.15) ax = plt.gca() ax.add_collection(collection) xmin, xmax = np.amin(verts[:, 1]), np.amax(verts[:, 1]) ymin, ymax = np.amin(verts[:, 0]), np.amax(verts[:, 0]) ax.set_xlim([xmin - 1, xmax + 1]) ax.set_ylim([ymin - 1, ymax + 1])
def poly_plot(verts, cmap=None, sampled=None, view_angles=[10, 270], outdir='./', outname='vert_', sampling=10, format='eps'): plt.figure() ax = plt.gca(projection='3d') if cmap is not None: poly = PolyCollection(verts[::sampling], facecolors=cmap[::sampling]) else: poly = PolyCollection(verts[::sampling]) poly.set_alpha(0.7) poly.set_edgecolor('none') ax.add_collection3d(poly, zs=sampled[:, 0], zdir='y') if sampled is not None: tticks = np.arange(0, sampled[:, 0].max() + 1, sampled[:, 0].max() / 2) xticks = np.arange(0, 301, 100) zticks = np.arange(0, sampled[:, 6].max() + 1, sampled[:, 6].max() / 2) ax.set_yticks(tticks) ax.set_xticks(xticks) ax.set_xlim3d(0, 300.0) ax.set_ylim3d(0, sampled[:, 0].max()) ax.set_zlim3d(0, sampled[:, 6].max()) ax.set_xlabel('$x$', linespacing=3.2) ax.set_ylabel('$t$', linespacing=3.2) ax.set_zlabel('$I$', linespacing=3.2) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') ax.zaxis.set_ticks_position('none') ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) plt.draw() for v, view in enumerate(view_angles): ax.view_init(elev=view[0], azim=view[1]) fig_name = outname + str(view[0]) + '_' + str(view[1]) plt.savefig(os.path.join(outdir, fig_name + '.' + format), format=format, dpi=320, bbox_inches='tight') return
def plot_mic_patches(self, plotType, minConfidence): indx = self.snp[:, 9] >= minConfidence minsw = self.sw / float(2**self.snp[0, 4]) tsw1 = minsw * 0.5 tsw2 = -minsw * 0.5 * 3**0.5 ntri = len(self.snp) if plotType == 2: fig, ax = plt.subplots() if self.bpatches == False: xy = self.snp[:, :2] tmp = np.asarray([[tsw1] * ntri, (-1)**self.snp[:, 3] * tsw2]).transpose() tris = np.asarray([[[0, 0]] * ntri, [[minsw, 0]] * ntri, tmp]) self.patches = np.swapaxes(tris + xy, 0, 1) self.bpatches = True p = PolyCollection(self.patches[indx], cmap='viridis') p.set_array(self.color2[indx]) p.set_edgecolor('face') ax.add_collection(p) ax.set_xlim([-0.6, 0.6]) ax.set_ylim([-0.6, 0.6]) fig.colorbar(p, ax=ax) plt.show() if plotType == 1: fig, ax = plt.subplots() N = len(self.snp) mat = np.empty([N, 3, 3]) quat = np.empty([N, 4]) rod = np.empty([N, 3]) if self.bcolor1 == False: for i in range(N): mat[i, :, :] = RotRep.EulerZXZ2Mat(self.snp[i, 6:9] / 180.0 * np.pi) quat[i, :] = RotRep.quaternion_from_matrix(mat[i, :, :]) rod[i, :] = RotRep.rod_from_quaternion(quat[i, :]) self.color1 = (rod + np.array([1, 1, 1])) / 2 self.bcolor1 = True if self.bpatches == False: xy = self.snp[:, :2] tmp = np.asarray([[tsw1] * ntri, (-1)**self.snp[:, 3] * tsw2]).transpose() tris = np.asarray([[[0, 0]] * ntri, [[minsw, 0]] * ntri, tmp]) self.patches = np.swapaxes(tris + xy, 0, 1) self.bpatches = True p = PolyCollection(self.patches[indx], cmap='viridis') p.set_color(self.color1[indx]) ax.add_collection(p) ax.set_xlim([-0.6, 0.6]) ax.set_ylim([-0.6, 0.6]) plt.show()
def plot_polygons(verts, colors, ax=None, edgecolor=None): """ `verts` is a sequence of ( verts0, verts1, ...) where verts_i is a sequence of xy tuples of vertices, or an equivalent numpy array of shape (nv, 2). `c` is a sequence of (color0, color1, ...) where color_i is a color, represented by a hex string (7 characters #xxxxxx). Creates a PolygonCollection object in the axis `ax`.""" if ax is None: fig = plt.gcf() ax = fig.add_subplot(1,1,1) pc = PolyCollection(verts) pc.set_edgecolor(edgecolor) pc.set_facecolor(colors) ax.add_collection(pc) ax.set_xlabel('X axis') ax.set_ylabel('Y axis')
def draw_colorbar(self, orientation): self.axes.clear() self.axes.set_axis_off() if orientation is "vertical": bin_height = 0.99 / len(self.color) barverts = tuple(((0.89, i*bin_height+0.005), (0.99, i*bin_height+0.005), (0.99, (i+1)*bin_height+0.005), (0.89, (i+1)*bin_height+0.005)) for i in range(len(self.color))) for i in range(len(self.bin)): self.axes.text(1.00, (i+1)*bin_height - 0.01, str(self.bin[i])) else: bin_width = 0.99 / len(self.color) barverts = tuple(((i*bin_width+0.005, 0.005), (i*bin_width+0.005, 0.105), ((i+1)*bin_width+0.005, 0.105), ((i+1)*bin_width+0.005, 0.005)) for i in range(len(self.color))) for i in range(len(self.bin)): self.axes.text((i+1)*bin_width - 0.015, -0.06, str(self.bin[i])) bar = PolyCollection(barverts) bar.set_edgecolor('black') bar.set_facecolor(self.color) bar.set_linewidth(0.5) self.axes.add_collection(bar)
def plot_geocol_mpl(gc, color=None, facecolor='0.3', edgecolor='0.7', alpha=1., linewidth=0.2, marker='o', marker_size=20, ax=None, figsize=(9, 9)): ''' Plot geographical data from the `geometry` column of a PySAL geotable to a matplotlib backend. ... Parameters ---------- gc : DataFrame GeoCol with data to be plotted. color : str/tuple/Series [Optional. Default=None] Wrapper that sets both `facecolor` and `edgecolor` at the same time. If set, `facecolor` and `edgecolor` are ignored. It allows for either a single color or a Series of the same length as `gc` with colors, indexed on `gc.index`. facecolor : str/tuple/Series [Optional. Default='0.3'] Color for polygons and points. It allows for either a single color or a Series of the same length as `gc` with colors, indexed on `gc.index`. edgecolor : str/tuple/Series [Optional. Default='0.7'] Color for the polygon and point edges. It allows for either a single color or a Series of the same length as `gc` with colors, indexed on `gc.index`. alpha : float/Series [Optional. Default=1.] Transparency. It allows for either a single value or a Series of the same length as `gc` with colors, indexed on `gc.index`. linewidth : float/Series [Optional. Default=0.2] Width(s) of the lines in polygon and line plotting (not applicable to points). It allows for either a single value or a Series of the same length as `gc` with colors, indexed on `gc.index`. marker : 'o' marker_size : int ax : AxesSubplot [Optional. Default=None] Pre-existing axes to which append the collections and setup figsize : tuple w,h of figure ''' geom = type(gc.iloc[0]) if color is not None: facecolor = edgecolor = color draw = False if not ax: f, ax = plt.subplots(1, figsize=figsize) draw = True # Geometry plotting patches = [] ids = [] # Polygons if geom == ps.cg.shapes.Polygon: for id, shape in gc.iteritems(): for ring in shape.parts: xy = np.array(ring) patches.append(xy) ids.append(id) mpl_col = PolyCollection(patches) # Lines elif geom == ps.cg.shapes.Chain: for id, shape in gc.iteritems(): for xy in shape.parts: patches.append(xy) ids.append(id) mpl_col = LineCollection(patches) facecolor = 'None' # Points elif geom == ps.cg.shapes.Point: edgecolor = facecolor xys = np.array(zip(*gc)).T ax.scatter(xys[:, 0], xys[:, 1], marker=marker, s=marker_size, c=facecolor, edgecolors=edgecolor, linewidths=linewidth) mpl_col = None # Styling mpl collection (polygons & lines) if mpl_col: if type(facecolor) is pd.Series: facecolor = facecolor.reindex(ids) mpl_col.set_facecolor(facecolor) if type(edgecolor) is pd.Series: edgecolor = edgecolor.reindex(ids) mpl_col.set_edgecolor(edgecolor) if type(linewidth) is pd.Series: linewidth = linewidth.reindex(ids) mpl_col.set_linewidth(linewidth) if type(alpha) is pd.Series: alpha = alpha.reindex(ids) mpl_col.set_alpha(alpha) ax.add_collection(mpl_col, autolim=True) ax.autoscale_view() ax.set_axis_off() if draw: plt.axis('equal') plt.show() return None
# Now try plotting speed and vectors with Basemap using a PolyCollection m = Basemap(projection='merc', llcrnrlat=lat.min(), urcrnrlat=lat.max(), llcrnrlon=lon.min(), urcrnrlon=lon.max(), lat_ts=lat.mean(), resolution=None) # project from lon,lat to mercator xnode, ynode = m(lon, lat) xc, yc = m(lonc, latc) # create a TRI object with projected coordinates tri = Tri.Triangulation(xnode, ynode, triangles=nv) # make a PolyCollection using triangles verts = concatenate((tri.x[tri.triangles][..., None], tri.y[tri.triangles][..., None]), axis=2) collection = PolyCollection(verts) collection.set_edgecolor('none') # <codecell> timestamp=start.strftime('%Y-%m-%d %H:%M:%S') # <codecell> # set the magnitude of the polycollection to the speed collection.set_array(mag) collection.norm.vmin=0 collection.norm.vmax=0.5 # <codecell> fig = plt.figure(figsize=(12,12))
conc[k]))) # log scale for the concentrations ## Create the figure fig, ax = plt.subplots() plt.ylim(0, amax.max()) plt.xlim(0, bmax.max()) ## Process the offsets and create the rectangle collection offsets = np.c_[x, y] col = PolyCollection(verts, offsets=offsets, transOffset=mtrans.IdentityTransform(), offset_position="data", cmap="spring") col.set_array(c) col.set_edgecolor('k') col.set_linewidth(0.5) ax.add_collection(col) ## Set axis labels ax.set_xlabel("Vacancy Cluster Size", fontsize=22) ax.set_ylabel("Helium Cluster Size", fontsize=22) ax.tick_params(axis='both', which='major', labelsize=20) ## The colorbar cbar = fig.colorbar(col) cbar.set_label("log(# / nm3)", fontsize=22) cbar.ax.tick_params(axis='y', labelsize=20) plt.show()
def plot_mic_patches(self, plotType, minConfidence, maxConfidence, indices): indx = [] for i in range(0, len(self.snp)): if self.snp[i, 9] >= minConfidence and self.snp[ i, 9] <= maxConfidence and i in indices: indx.append(i) #indx=minConfidence<=self.snp[:,9]<=maxConfidence minsw = self.sw / float(2**self.snp[0, 4]) tsw1 = minsw * 0.5 tsw2 = -minsw * 0.5 * 3**0.5 ntri = len(self.snp) if plotType == 2: fig, ax = plt.subplots() if self.bpatches == False: xy = self.snp[:, :2] tmp = np.asarray([[tsw1] * ntri, (-1)**self.snp[:, 3] * tsw2]).transpose() tris = np.asarray([[[0, 0]] * ntri, [[minsw, 0]] * ntri, tmp]) self.patches = np.swapaxes(tris + xy, 0, 1) self.bpatches = True p = PolyCollection(self.patches[indx], cmap='viridis') p.set_array(self.color2[indx]) p.set_edgecolor('face') ax.add_collection(p) ax.set_xlim([-0.6, 0.6]) ax.set_ylim([-0.6, 0.6]) fig.colorbar(p, ax=ax) plt.show() if plotType == 1: fig, ax = plt.subplots() N = len(self.snp) mat = np.empty([N, 3, 3]) quat = np.empty([N, 4]) rod = np.empty([N, 3]) if self.bcolor1 == False: maxr = 0.0 minr = 0.0 maxg = 0.0 ming = 0.0 maxb = 0.0 minb = 0.0 for i in range(N): if i in indx: mat[i, :, :] = RotRep.EulerZXZ2Mat(self.snp[i, 6:9] / 180.0 * np.pi) quat[i, :] = RotRep.quaternion_from_matrix( mat[i, :, :]) rod[i, :] = RotRep.rod_from_quaternion(quat[i, :]) if i == indx[0]: maxr = rod[i, 0] minr = rod[i, 0] maxg = rod[i, 1] ming = rod[i, 1] maxb = rod[i, 2] minb = rod[i, 2] else: if rod[i, 0] > maxr: maxr = rod[i, 0] elif rod[i, 0] < minr: minr = rod[i, 0] if rod[i, 1] > maxg: maxg = rod[i, 1] elif rod[i, 1] < ming: ming = rod[i, 1] if rod[i, 2] > maxb: maxb = rod[i, 2] elif rod[i, 2] < minb: minb = rod[i, 2] else: rod[i, :] = [0.0, 0.0, 0.0] print "Current rod values: ", rod maxrgb = [maxr, maxg, maxb] minrgb = [minr, ming, minb] colors = rod for j in range(N): for k in range(0, 3): colors[j, k] = (rod[j, k] - minrgb[k]) / (maxrgb[k] - minrgb[k]) self.color1 = colors print "Color: ", self.color1 #self.bcolor1=True if self.bpatches == False: xy = self.snp[:, :2] tmp = np.asarray([[tsw1] * ntri, (-1)**self.snp[:, 3] * tsw2]).transpose() tris = np.asarray([[[0, 0]] * ntri, [[minsw, 0]] * ntri, tmp]) self.patches = np.swapaxes(tris + xy, 0, 1) self.bpatches = True p = PolyCollection(self.patches[indx], cmap='viridis') p.set_color(self.color1[indx]) ax.add_collection(p) ax.set_xlim([-0.6, 0.6]) ax.set_ylim([-0.6, 0.6]) plt.show()
y = z y = np.hstack((zr, z, zr)) # add zero x = np.arange(len(y)) # print blobs # print x # print y # print x[-1] # print edges verts.append(zip(x, y)) verts = np.array(verts) n, p, d = verts.shape poly = PolyCollection(verts, facecolors=[solidColor for i in range(n)]) poly.set_alpha(alpha) poly.set_edgecolor('black') poly.set_linewidth(.1) ax.add_collection3d(poly, zs=np.arange(n), zdir='y') ax.set_xlabel('ClusterSize') ax.set_xlim3d(0, p) ax.set_ylabel('Time (ms)') ax.set_ylim3d(0, n) ax.set_zlabel('Cluster Counts') ax.set_zlim3d(0, 1.2 * maxz) ax.set_xticks(np.array(range(0, clustersize * 3, 3)) + 0.5) ax.set_xticklabels(range(0, clustersize)) print edges print ax.get_xticks()
def smcglobl(cel, nvrts, ncels, svrts, scels, colrs, config, Arctic=None, mdlname='SMC', buoys=None, psfile='output.ps', paprtyp='a3'): """ ## The smcglobl function plots a global view of a given smc grid. ## cel is the full cell array in shape(nc, 5). ## JGLi04Mar2019 """ ## Degree to radian conversion parameter. d2rad = np.pi / 180.0 ## Global plot configuration parameters. rdpols = config[0] sztpxy = config[1] rngsxy = config[2] clrbxy = config[3] if (Arctic is not None): ncabgm = config[4] ## Maximum mapping radius. radius = rdpols[0] pangle = rdpols[1] plon = rdpols[2] plat = rdpols[3] ## Outline circle at equator ciran = np.arange(1081) * d2rad / 3.0 xcirc = radius * np.cos(ciran) ycirc = radius * np.sin(ciran) ## Define depth to color index conversion parameters and marks. ## Use only first 131 colors in colrs(0:255). depth, factr, cstar, marks, ncstr, nclrm = scale_depth(nclrm=131) ## Cell color is decided by its depth value, dry cells use default 0 color. nc = cel.shape[0] ndeps = np.zeros((nc), dtype=np.int) for j in range(nc): if (cel[j, 4] > 0): ndeps[j] = ncstr + np.rint( (cstar - np.log10(cel[j, 4])) * factr).astype(np.int) #ndeps = ncstr + np.rint( (cstar-np.log10(cel[:,4]))*factr ).astype(np.int) if (Arctic is not None): na = int(ncabgm[1]) nb = int(ncabgm[2]) jm = int(ncabgm[3]) ## Set up first subplot and axis for northern hemisphere print(" Drawing north hemisphere cells ... ") fig = plt.figure(figsize=sztpxy[0:2]) ax1 = fig.add_subplot(1, 2, 1) ax1.set_aspect('equal') ax1.set_autoscale_on(False) ax1.set_axis_off() plt.subplots_adjust(left=0.02, bottom=0.02, right=0.98, top=0.95) plt.subplots_adjust(wspace=0.02, hspace=0.01) xprop = {'xlim': rngsxy[0:2], 'xlabel': 'Nothing'} yprop = {'ylim': rngsxy[2:4], 'ylabel': 'Nothing'} ax1.set(**xprop) ax1.set(**yprop) ax1.plot(xcirc, ycirc, 'b-') ## Select cells for one subplot and create verts and pcolr. pcface = [] pcedge = [] for i in ncels: if (Arctic is not None) and (cel[i, 1] == Arctic): # Mark the arctic map-east reference region by first ring of its boundary cells pcface.append(colrs(246)) pcedge.append(colrs(246)) #elif( Arctic is not None ) and ( cel[i,1] == jm ): # # Mark the arctic cells # pcface.append(colrs(168)) # pcedge.append(colrs(168)) else: pcface.append(colrs(255)) pcedge.append(colrs(ndeps[i])) ## Draw this hemisphere cells smcpoly = PolyCollection(nvrts) smcpoly.set_facecolor(pcface) smcpoly.set_edgecolor(pcedge) smcpoly.set_linewidth(0.2) ax1.add_collection(smcpoly) ## Draw colorbar for ax1. xkeys, ykeys, clrply = colrboxy(clrbxy, colrs, marks, nclrm=nclrm) ax1.add_collection(clrply) for i in range(len(depth)): m = marks[i] plt.text(xkeys[m], ykeys[0] + 1.15 * (ykeys[1] - ykeys[0]), str(depth[i]), horizontalalignment='center', fontsize=11, color='b') #rotation=-90,verticalalignment='center', fontsize=11, color='b' ) plt.text(xkeys[marks[0]], ykeys[0] + 2.2 * (ykeys[1] - ykeys[0]), 'Depth m', horizontalalignment='left', fontsize=15, color='k') #rotation=-90,verticalalignment='center', fontsize=15, color='k' ) # Overlay buoy sites on grid map if buoy file is provided. if (buoys is not None): hdr, buoyll = readtext(buoys) nmbu = long(hdr[0]) buoyids = buoyll[:, 0].astype(str) buoylat = buoyll[:, 1].astype(np.float) buoylon = buoyll[:, 2].astype(np.float) #; Convert slat slon to elat elon with given new pole elat, elon, sxc, syc = steromap(buoylat, buoylon, plat, plon, Pangl=pangle) #; Mark buoy position on map print(' Selected buoys on north hemisphere ...') for i in range(nmbu): if ((elat[i] >= 0.0) and (rngsxy[0] < sxc[i] < rngsxy[1]) and (rngsxy[2] < syc[i] < rngsxy[3])): print(' {:6} {:8.3f} {:8.3f}'.format(buoyids[i], buoylat[i], buoylon[i])) txtsz = int(abs(np.sin(elat[i] * d2rad) * 12.0)) plt.text(sxc[i], syc[i], 'r', fontsize=txtsz, horizontalalignment='center', color='r') plt.text(sxc[i], syc[i], '.', fontsize=txtsz * 2, horizontalalignment='center', color='r') ## Southern hemisphere print(" Drawing south hemisphere cells ... ") ax2 = fig.add_subplot(1, 2, 2) ax2.set_aspect('equal') ax2.axis('off') plt.subplots_adjust(left=0.02, bottom=0.02, right=0.98, top=0.95) plt.subplots_adjust(wspace=0.02, hspace=0.01) ax2.set(**xprop) ax2.set(**yprop) ax2.plot(xcirc, ycirc, 'b-') ## Select cells for one subplot and create verts and pcolr. pcface = [] pcedge = [] for i in scels: pcface.append(colrs(255)) pcedge.append(colrs(ndeps[i])) ## Generate polygon collections for southern hemisphere smcpoly = PolyCollection(svrts) smcpoly.set_facecolor(pcface) smcpoly.set_edgecolor(pcedge) smcpoly.set_linewidth(0.2) ax2.add_collection(smcpoly) ## Put cell information inside plot tpx = sztpxy[2] tpy = sztpxy[3] dpy = 0.6 plt.text(tpx, tpy + dpy * 0.5, mdlname + ' Grid', horizontalalignment='center', fontsize=15, color='k') plt.text(tpx, tpy + dpy * 2.0, 'NC=' + str(nc), horizontalalignment='center', fontsize=13, color='r') if (Arctic is not None): plt.text(tpx, tpy + dpy * 3.0, 'NA=' + str(na), horizontalalignment='center', fontsize=13, color='r') plt.text(tpx, tpy + dpy * 4.0, 'NB=' + str(nb), horizontalalignment='center', fontsize=13, color='r') ## Draw colorbar for ax2. xkeys, ykeys, clrply = colrboxy(clrbxy, colrs, marks, nclrm=nclrm) ax2.add_collection(clrply) for i in range(len(depth)): m = marks[i] plt.text(xkeys[m], ykeys[0] + 1.18 * (ykeys[1] - ykeys[0]), str(depth[i]), horizontalalignment='center', fontsize=11, color='b') #verticalalignment='center', fontsize=11, color='b' ) #rotation=-90,verticalalignment='center', fontsize=11, color='b' ) plt.text(xkeys[marks[-1]], ykeys[0] + 2.2 * (ykeys[1] - ykeys[0]), 'Depth m', horizontalalignment='right', fontsize=15, color='k') #rotation=-90,verticalalignment='center', fontsize=15, color='k' ) # Overlay buoy sites on grid map if buoy file is provided. if (buoys is not None): #; Mark buoy position on map print(' Selected buoys on south hemisphere ...') for i in range(nmbu): if ((elat[i] < 0.0) and (rngsxy[0] < -sxc[i] < rngsxy[1]) and (rngsxy[2] < syc[i] < rngsxy[3])): print(' {:6} {:8.3f} {:8.3f}'.format(buoyids[i], buoylat[i], buoylon[i])) txtsz = int(abs(np.sin(elat[i] * d2rad) * 12.0)) plt.text(-sxc[i], syc[i], 'r', fontsize=txtsz, horizontalalignment='center', color='r') plt.text(-sxc[i], syc[i], '.', fontsize=txtsz * 2, horizontalalignment='center', color='r') ## Refresh subplots and save them. plt.subplots_adjust(wspace=0.02, hspace=0.01) plt.savefig(psfile, dpi=None,facecolor='w',edgecolor='w', \ orientation='landscape',papertype=paprtyp,format='ps')
def __main__(request, actions, u, v, width, height, lonmax, lonmin, latmax, latmin, index, lon, lat, lonn, latn, nv): fig = Plot.figure(dpi=150, facecolor='none', edgecolor='none') fig.set_alpha(0) #ax = fig.add_subplot(111) projection = request.GET["projection"] m = Basemap( llcrnrlon=lonmin, llcrnrlat=latmin, urcrnrlon=lonmax, urcrnrlat=latmax, projection=projection, #lat_0 =(latmax + latmin) / 2, lon_0 =(lonmax + lonmin) / 2, lat_ts=0.0, ) #lonn, latn = m(lonn, latn) m.ax = fig.add_axes([0, 0, 1, 1]) #fig.set_figsize_inches((20/m.aspect, 20.)) fig.set_figheight(5) fig.set_figwidth(5 / m.aspect) if "regrid" in actions: #import fvcom_compute.fvcom_stovepipe.regrid as regrid #wid = numpy.max((width, height)) #size = (lonmax - lonmin) / wid #hi = (latmax - latmin) / size #hi = math.ceil(hi) #reglon = numpy.linspace(numpy.negative(lonmin), numpy.negative(lonmax), wid) #reglon = numpy.negative(reglon) #reglat = numpy.linspace(latmin, latmax, hi) #if "pcolor" in actions: # mag = numpy.power(u.__abs__(), 2)+numpy.power(v.__abs__(), 2) # mag = numpy.sqrt(mag) # newvalues = regrid.regrid(mag, lonn, latn, nv, reglon, reglat, size) # reglon, reglat = numpy.meshgrid(reglon, reglat) # grid = reorderArray(newvalues, len(reglat[:,1]), len(reglon[1,:])) # ax = fig.add_subplot(111) # ax.pcolor(reglon, reglat, grid) #if "contours" in actions: # mag = numpy.power(u.__abs__(), 2)+numpy.power(v.__abs__(), 2) # mag = numpy.sqrt(mag) # newvalues = regrid.regrid(mag, lonn, latn, nv, reglon, reglat, size) # reglon, reglat = numpy.meshgrid(reglon, reglat) # grid = reorderArray(newvalues, len(reglat[:,1]), len(reglon[1,:])) # ax = fig.add_subplot(111) # ax.contourf(reglon, reglat, grid) #if "vectors" in actions: # newv = regrid.regrid(v, lonn, latn, nv, reglon, reglat, size) # newu = regrid.regrid(u, lonn, latn, nv, reglon, reglat, size) # mag = numpy.power(newu.__abs__(), 2)+numpy.power(newv.__abs__(), 2) # mag = numpy.sqrt(mag) # ax = fig.add_subplot(111) # ax.quiver(reglon, reglat, newu, newv, mag, pivot='mid') pass else: if "vectors" in actions: mag = numpy.power(u.__abs__(), 2) + numpy.power(v.__abs__(), 2) mag = numpy.sqrt(mag) #ax = fig.add_subplot(111) #ax.quiver(lon, lat, u, v, mag, pivot='mid') lon, lat = m(lon, lat) m.quiver(lon, lat, u, v, mag, pivot='mid') ax = Plot.gca() elif "contours" in actions: mag = numpy.power(u.__abs__(), 2) + numpy.power(v.__abs__(), 2) mag = numpy.sqrt(mag) ax = fig.add_subplot(111) ax.tricontourf(lon, lat, mag) elif "facets" in actions: #projection = request.GET["projection"] #m = Basemap(llcrnrlon=lonmin, llcrnrlat=latmin, # urcrnrlon=lonmax, urcrnrlat=latmax, projection=projection, # lat_0 =(latmax + latmin) / 2, lon_0 =(lonmax + lonmin) / 2, # ) lonn, latn = m(lonn, latn) #m.ax = fig.add_axes([0, 0, 1, 1]) #fig.set_figheight(20) #fig.set_figwidth(20/m.aspect) #m.drawmeridians(numpy.arange(0,360,1), color='0.5',) tri = Tri.Triangulation(lonn, latn, triangles=nv) mag = numpy.power(u.__abs__(), 2) + numpy.power(v.__abs__(), 2) mag = numpy.sqrt(mag) #ax.tripcolor(lon, lat, mag, shading="") #collection = PolyCollection(numpy.asarray([(lonn[node1],latn[node1]),(lonn[node2],latn[node2]),(lonn[node3],latn[node3])])) verts = numpy.concatenate((tri.x[tri.triangles][...,numpy.newaxis],\ tri.y[tri.triangles][...,numpy.newaxis]), axis=2) collection = PolyCollection(verts) collection.set_array(mag) collection.set_edgecolor('none') ax = Plot.gca() #m.add_collection(collection) #ax = Plot.gca() #m2.ax.add_collection(collection) ax.add_collection(collection) lonmax, latmax = m(lonmax, latmax) lonmin, latmin = m(lonmin, latmin) ax.set_xlim(lonmin, lonmax) ax.set_ylim(latmin, latmax) ax.set_frame_on(False) ax.set_clip_on(False) ax.set_position([0, 0, 1, 1]) #Plot.yticks(visible=False) #Plot.xticks(visible=False) #Plot.axis('off') canvas = Plot.get_current_fig_manager().canvas response = HttpResponse(content_type='image/png') canvas.print_png(response) return response
def smclocal(cel, verts, ncels, colrs, config, Arctic=None, mdlname='SMC', buoys=None, psfile='output.ps', paprorn='portrait', paprtyp='a3'): """ ## The smclocal function plots a local region of a given smc grid. ## cel is the full cell array in shape(nc, 5). ## JGLi04Mar2019 """ # Degree to radian conversion parameter. d2rad = np.pi / 180.0 # Local plot configuration parameters rdpols = config[0] sztpxy = config[1] rngsxy = config[2] clrbxy = config[3] if (Arctic): ncabgm = config[4] # Maximum mapping radius. radius = rdpols[0] pangle = rdpols[1] plon = rdpols[2] plat = rdpols[3] # Define depth to color index conversion parameters and marks. # Use only first 131 colors in colrs(0:255). depth, factr, cstar, marks, ncstr, nclrm = scale_depth(nclrm=136) # Cell color is decided by its depth value. nc = cel.shape[0] ndeps = np.zeros((nc), dtype=np.int) for j in range(nc): if (cel[j, 4] > -11): ndeps[j] = ncstr + np.rint( (cstar - np.log10(cel[j, 4] + 11)) * factr).astype(np.int) #ndeps = ncstr + np.rint( (cstar-np.log10(cel[:,4]))*factr ).astype(np.int) if (Arctic is not None): na = int(ncabgm[1]) nb = int(ncabgm[2]) jm = int(ncabgm[3]) # Workout output file format from its extension #for i in np.arange(len(psfile))[::-1]: # if( psfile[i] == '.' ): # psfmt = psfile[i+1:] # break #print " Output file format will be "+psfmt # Python plt.savefig will do this automatically. # Use selected cells to draw the plot. fig = plt.figure(figsize=sztpxy[0:2]) ax = fig.add_subplot(1, 1, 1) yprop = {'ylim': rngsxy[2:4], 'ylabel': ''} xprop = {'xlim': rngsxy[0:2], 'xlabel': ''} ax.set(**xprop) ax.set(**yprop) ax.set_aspect('equal') ax.set_autoscale_on(False) ax.set_axis_off() plt.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0) # Create color array for this plot pcface = [] pcedge = [] for i in ncels: if (Arctic is not None) and (cel[i, 1] == Arctic): # Mark the arctic map-east reference region by first ring of its boundary cells pcface.append(colrs(246)) pcedge.append(colrs(246)) #elif( Arctic is not None ) and ( cel[i,1] == jm ): # # Mark the arctic cells # pcface.append(colrs(168)) # pcedge.append(colrs(168)) else: pcedge.append(colrs(ndeps[i] + 10)) pcface.append(colrs(ndeps[i])) #pcface.append(colrs(255)) #pcedge.append(colrs(ndeps[i])) # Create PolyCollection from selected verts and define edge and face color. polynorth = PolyCollection(verts) polynorth.set_facecolor(pcface) polynorth.set_edgecolor(pcedge) polynorth.set_linewidth(0.2) # Draw the selected cells as colored polygons. ax.add_collection(polynorth) # Draw colorbar inside plot. xkeys, ykeys, clrply = colrboxy(clrbxy, colrs, marks, nclrm=nclrm) ax.add_collection(clrply) dkx = clrbxy[2] dky = clrbxy[3] for i in range(len(depth)): m = marks[i] if (dkx < dky): plt.text(xkeys[0] + 1.15 * dkx, ykeys[m], str(depth[i]), verticalalignment='center', fontsize=11, color='b') else: plt.text(xkeys[m], ykeys[0] + 1.15 * dky, str(depth[i]), horizontalalignment='center', fontsize=11, color='b') if (dkx < dky): plt.text(xkeys[0] + 1.9 * dkx, ykeys[marks[2]], 'Depth m', rotation=-90, verticalalignment='center', fontsize=15, color='k') else: plt.text(xkeys[marks[2]], ykeys[0] + 1.9 * dky, 'Depth m', rotation=0, horizontalalignment='center', fontsize=15, color='k') # Put cell information inside plot tpx = sztpxy[2] tpy = sztpxy[3] dpy = -0.6 plt.text(tpx, tpy + dpy * 1, mdlname + ' Grid', horizontalalignment='center', fontsize=15, color='k') plt.text(tpx, tpy + dpy * 2, 'NC=' + str(nc), horizontalalignment='center', fontsize=13, color='r') if (Arctic is not None): plt.text(tpx, tpy + dpy * 3, 'NA=' + str(na), horizontalalignment='center', fontsize=13, color='r') plt.text(tpx, tpy + dpy * 4, 'NB=' + str(nb), horizontalalignment='center', fontsize=13, color='r') # Overlay buoy sits on grid map if buoy file is provided. if (buoys is not None): hdr, buoyll = readtext(buoys) nmbu = int(hdr[0]) buoyids = buoyll[:, 0].astype(str) buoylat = buoyll[:, 1].astype(np.float) buoylon = buoyll[:, 2].astype(np.float) # Convert slat slon to elat elon with given new pole elat, elon, sxc, syc = steromap(buoylat, buoylon, plat, plon, Pangl=pangle) # Mark buoy position on map print(' Selected buoys in this plot:') for i in range(nmbu): if ((elat[i] >= 25.0) and (rngsxy[0] < sxc[i] < rngsxy[1]) and (rngsxy[2] < syc[i] < rngsxy[3])): print(' {:6} {:8.3f} {:8.3f}'.format(buoyids[i], buoylat[i], buoylon[i])) txtsz = int(abs(np.sin(elat[i] * d2rad) * 12.0)) plt.text(sxc[i], syc[i], 'r', fontsize=txtsz, horizontalalignment='center', color='r') plt.text(sxc[i], syc[i], '.', fontsize=txtsz * 2, horizontalalignment='center', color='r') # Save plot as ps file print(" Save the smc grid local plot ... ") plt.savefig(psfile, dpi=None,facecolor='w',edgecolor='w', \ orientation=paprorn,papertype=paprtyp,format='ps')
def swhglobl(swhs, nvrts, ncels, svrts, scels, colrs, config, mdlname='SMC', datx='2018010106', psfile='output.ps', paprtyp='a3'): """ ## Draw global swh plot with given polycollections and cell ## array. Output as A3 ps file. JGLi28Feb2019 ## """ # Degree to radian conversion parameter. d2rad = np.pi / 180.0 # Global plot configuration parameters. rdpols = config[0] sztpxy = config[1] rngsxy = config[2] clrbxy = config[3] ncabgm = config[4] # Maximum mapping radius. radius = rdpols[0] pangle = rdpols[1] plon = rdpols[2] plat = rdpols[3] # Outline circle at equator ciran = np.arange(1081) * d2rad / 3.0 xcirc = radius * np.cos(ciran) ycirc = radius * np.sin(ciran) # Set up wave height scale and marks with colrs.N. # colrs.N returns colrs' total number of colors 256. waveht, factor, residu, marks, ncstr, nclrm = scale_swh(nclrm=colrs.N) resmn1 = residu - 1.0 nswh0 = ncstr + int(factor * np.log(-resmn1 + residu)) #print (' factor, residu, resmn1, nswh0 = {} {} {} {: d}' #.format(factor, residu, resmn1, nswh0) ) # Some constant variables for plots. xprop = {'xlim': rngsxy[0:2], 'xlabel': ''} yprop = {'ylim': rngsxy[2:4], 'ylabel': ''} if True: # Work out max and min values, excluding missing data (-999.0) cmax = swhs.max() cmin = swhs[swhs > -999.0].min() print(' swh range %f, %f' % (cmin, cmax)) cmxs = 'SWHmx = %6.2f m' % cmax cmns = 'SWHmn = %10.3E' % cmin # Reset missing values (-999.0) to be -resmn1 swhs[swhs < -resmn1] = -resmn1 # Trim large values into plot range if any swhs[swhs > 32.0] = 32.0 # Convert swhs with logarithm scale. icnf = np.rint(factor * np.log(swhs + residu)) nswh = np.array(icnf, dtype=np.int) print(" Drawing " + psfile) # Set up first subplot and axis for northern hemisphere fig = plt.figure(figsize=sztpxy[0:2]) ax1 = fig.add_subplot(1, 2, 1) ax1.set_aspect('equal') ax1.set_autoscale_on(False) ax1.set_axis_off() plt.subplots_adjust(left=0.02, bottom=0.02, right=0.98, top=0.95) plt.subplots_adjust(wspace=0.02, hspace=0.01) ax1.set(**xprop) ax1.set(**yprop) ax1.plot(xcirc, ycirc, 'b-') # Use loaded verts to setup PolyCollection. polynorth = PolyCollection(nvrts) # Create color array for this plot pcface = [] pcedge = [] for i in ncels: if (nswh[i] == nswh0): pcface.append(colrs(255)) pcedge.append(colrs(0)) else: pcface.append(colrs(nswh[i])) pcedge.append(colrs(nswh[i])) #smcpoly.set_color(pcolr) ## This line defines both edge and face color. polynorth.set_facecolor(pcface) polynorth.set_edgecolor(pcedge) polynorth.set_linewidth(0.2) ax1.add_collection(polynorth) # Draw colorbar for ax1. xkeys, ykeys, clrply = colrboxy(clrbxy, colrs, marks) ax1.add_collection(clrply) for i in range(len(waveht)): m = marks[i] plt.text(xkeys[m], ykeys[0] + 1.18 * (ykeys[1] - ykeys[0]), str(waveht[i]), horizontalalignment='center', fontsize=11, color='b') #rotation=-90,verticalalignment='center', fontsize=11, color='b' ) plt.text(xkeys[marks[0]], ykeys[0] + 2.2 * (ykeys[1] - ykeys[0]), 'SWH m', horizontalalignment='left', fontsize=15, color='k') #rotation=-90,verticalalignment='center', fontsize=15, color='k' ) # Southern hemisphere subplot. ax2 = fig.add_subplot(1, 2, 2) ax2.set_aspect('equal') ax2.axis('off') plt.subplots_adjust(left=0.02, bottom=0.02, right=0.98, top=0.95) plt.subplots_adjust(wspace=0.02, hspace=0.01) ax2.set(**xprop) ax2.set(**yprop) ax2.plot(xcirc, ycirc, 'b-') # Use loaded verts to set up PolyCollection. polysouth = PolyCollection(svrts) # Create color array for this plot pcface = [] pcedge = [] for i in scels: if (nswh[i] == nswh0): pcface.append(colrs(255)) pcedge.append(colrs(0)) else: pcface.append(colrs(nswh[i])) pcedge.append(colrs(nswh[i])) # smcpoly.set_color(pcolr) ## This line defines both edge and face color. polysouth.set_facecolor(pcface) polysouth.set_edgecolor(pcedge) polysouth.set_linewidth(0.2) ax2.add_collection(polysouth) # Put statistic information inside subplot ax2 tpx = sztpxy[2] tpy = sztpxy[3] dpy = 0.6 plt.text(tpx, 9.0, mdlname + ' SWH', horizontalalignment='center', fontsize=19, color='r') plt.text(tpx, tpy + dpy * 1.0, cmns, horizontalalignment='center', fontsize=15, color='b') plt.text(tpx, tpy + dpy * 2.0, cmxs, horizontalalignment='center', fontsize=15, color='r') plt.text(tpx, tpy + dpy * 3.0, datx, horizontalalignment='center', fontsize=17, color='k') # Draw colorbar for ax2. xkeys, ykeys, clrply = colrboxy(clrbxy, colrs, marks) ax2.add_collection(clrply) for i in range(len(waveht)): m = marks[i] plt.text(xkeys[m], ykeys[0] + 1.18 * (ykeys[1] - ykeys[0]), str(waveht[i]), horizontalalignment='center', fontsize=13, color='b') #rotation=-90,verticalalignment='center', fontsize=11, color='b' ) plt.text(xkeys[marks[-1]], ykeys[0] + 2.2 * (ykeys[1] - ykeys[0]), 'SWH m', horizontalalignment='right', fontsize=15, color='k') #rotation=-90,verticalalignment='center', fontsize=15, color='k' ) # Refresh subplots and save them. plt.subplots_adjust(wspace=0.02, hspace=0.01) plt.savefig(psfile, dpi=None, facecolor='w', edgecolor='w', orientation='landscape', papertype=paprtyp, format='ps') plt.close()
def genPlot(self, ax=None, filled=False, plot_var=None, cax_kws=None, cb_kws=None, txtloc=None, center=False, dotsize=0.008, mapext=None, vmin=None, vmax=None, vint=None, txtSize=7, cbtxtSize=None, linewidth=0.1): """ Generate plot for plot_var on SMC grid Args: ax (object): axis object filled (bool): fill cells or not plot_var (str): the parameter need to be plotted, of which valules determine the filled color cax_kws (dict): kws for colorbar location cb_kwds (dict): kws for colobar txtloc (str): loc of necessary text info. (x, y) center (bool): draw dots in each cell dotsize (int): the radius of Circles (for cell center dots) mapext (list): map bbox to zoom in the cartopy map vmin/vmax/vint (float): colorbar range/tick """ if not hasattr(self, 'poly'): self._genPoly() # -- plot setting if plot_var.lower() == 'depth': norm = mpl.colors.LogNorm(vmin=1, vmax=10000, clip=False) cmap = cmocean.cm.deep cbtl = 'Depth [m]' cticks = [1, 10, 100, 1000, 10000] elif plot_var.lower() == 'swh': if vmin is None: vmin = 0. if vmax is None: vmax = 6. if vint is None: vint = 1. norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax, clip=False) cmap = plt.get_cmap('viridis') cbtl = 'SWH [m]' cticks = np.arange(vmin, vmax+.1*vint, vint) elif plot_var.lower() == 'sx' or plot_var.lower() == 'sy': filled = True norm = mpl.colors.Normalize(vmin=0., vmax=100., clip=False) cmap = plt.get_cmap('viridis') cbtl = 'Obs. in {:s} dirc. [%]'.format(plot_var.lower()[1]) cticks = np.arange(0, 101, 20) elif plot_var.lower() == 'wspd': vmax = vmax if vmax else 40 vmin = vmin if vmin else 0. vint = vint if vint else 10. cmap = plt.get_cmap('plasma') norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax, clip=False) cbtl = 'Wind [m/s]' cticks = np.arange(vmin, vmax+.1*vint, vint) else: pass facecolor = None if filled else 'none' # -- cells if self.proj is not None: polyc = PolyCollection(self.poly, cmap=cmap, norm=norm, linewidth=linewidth, facecolor=facecolor) else: polyc = PolyCollection(self.poly, cmap=cmap, norm=norm, linewidth=linewidth, facecolor=facecolor, transform=ccrs.PlateCarree()) polyc.set_edgecolor('face') polyc.set_array(ma.masked_equal(getattr(self, plot_var), -999999)) ax.add_collection(polyc) # -- center dot of each cell # -- use 'o' or 's' to replace '.' if center: # use very small size for scatter/marker ax.scatter(self.clon, self.clat, s=dotsize, c=getattr(self, plot_var), marker='o', norm=norm, cmap=cmap, transform=ccrs.PlateCarree()) # circlec = PatchCollection([Circle((x, y), radius=radius) # for x, y in np.c_[self.clon, self.clat]], # edgecolor='none', cmap=cmap, norm=norm, # transform=ccrs.PlateCarree()) # circlec.set_array(getattr(self, plot_var)) # ax.add_collection(circlec) # -- lim axis ax.autoscale_view() # !!! Very important if mapext is not None: ax.set_extent(mapext, crs=ccrs.PlateCarree()) # -- colorbar if cax_kws is None: cax_kws = dict() btr = None if cax_kws.get('bbox_to_anchor') is None else ax.transAxes cax = inset_axes(ax, width=cax_kws.get('width', '40%'), height=cax_kws.get('height', '3%'), loc=cax_kws.get('loc', 2), # upper right bbox_to_anchor=cax_kws.get('bbox_to_anchor', None), bbox_transform=btr, borderpad=cax_kws.get('borderpad', None)) # units: fontsize #borderpad=cax_kws.get('borderpad', 2.)) # units: fontsize # This is causing a crash for some reason... if cb_kws is None: cb_kws=dict() cb = plt.colorbar(polyc, cax=cax, format='%d', orientation=cb_kws.get('orientation', 'horizontal')) cb.set_label(cbtl, size=txtSize) cb.set_ticks(cticks) if cbtxtSize is None: cbtxtSize = txtSize - 1 cb.ax.tick_params(labelsize=cbtxtSize) # -- cell info. if plot_var in ['depth', 'sx', 'sy']: info = ('{:s}\n' r'$\longmapsto$' '\n NL = {:d}\n N1 = {:d}\n N2 = {:d}\n N4 = {:d}').format( self.gid, self.NL, self.N1, self.N2, self.N4) if plot_var in ['swh', 'wspd']: try: timeStr = self.time.strftime('%Y-%m-%d %HZ') except: timeStr = str(self.time) info = '{:s}\n Max: {:.1f}\n Min: {:.1f}'.format( timeStr, getattr(self, plot_var).max(), getattr(self, plot_var).min()) if txtloc is None: txtloc = (0.1, 0.85) ax.text(txtloc[0], txtloc[1], info, ha='left', va='top', multialignment='left', transform=ax.transAxes, fontsize=txtSize, color='k')
def show_mesh_2d(axes, mesh, nodecolor='k', edgecolor='k', cellcolor='grey', aspect='equal', linewidths=1, markersize=20, showaxis=False, showcolorbar=False, cmap='gnuplot2'): axes.set_aspect(aspect) if showaxis == False: axes.set_axis_off() else: axes.set_axis_on() if (type(nodecolor) is np.ndarray) & np.isreal(nodecolor[0]): cmax = nodecolor.max() cmin = nodecolor.min() norm = colors.Normalize(vmin=cmin, vmax=cmax) mapper = cm.ScalarMappable(norm=norm, cmap=cmap) nodecolor = mapper.to_rgba(nodecolor) if (type(cellcolor) is np.ndarray) & np.isreal(cellcolor[0]): cmax = cellcolor.max() cmin = cellcolor.min() norm = colors.Normalize(vmin=cmin, vmax=cmax) mapper = cm.ScalarMappable(norm=norm, cmap=cmap) mapper.set_array(cellcolor) cellcolor = mapper.to_rgba(cellcolor) if showcolorbar: f = axes.get_figure() cbar = f.colorbar(mapper, shrink=0.5, ax=axes) node = mesh.node cell = mesh.ds.cell if mesh.meshtype is not 'polygon': if mesh.geo_dimension() == 2: poly = PolyCollection(node[cell, :]) else: poly = a3.art3d.Poly3DCollection(node[cell, :]) else: cellLocation = mesh.ds.cellLocation NC = mesh.number_of_cells() patches = [ Polygon(node[cell[cellLocation[i]:cellLocation[i + 1]], :], True) for i in range(NC) ] poly = PatchCollection(patches) poly.set_edgecolor(edgecolor) poly.set_linewidth(linewidths) poly.set_facecolors(cellcolor) if mesh.geo_dimension() == 2: box = np.zeros(4, dtype=np.float) else: box = np.zeros(6, dtype=np.float) box[0::2] = np.min(node, axis=0) box[1::2] = np.max(node, axis=0) axes.set_xlim(box[0:2]) axes.set_ylim(box[2:4]) if mesh.geo_dimension() == 3: axes.set_zlim(box[4:6]) return axes.add_collection(poly)
def plot_mic_patches(self, plotType=1, minConfidence=0, maxConfidence=1, limitang=False, angles=[]): indx = [] for i in range(0, len(self.snp)): if self.snp[i, 9] >= minConfidence and self.snp[i, 9] <= maxConfidence: indx.append(i) if limitang: indx = self.angle_limiter(indx, self.snp, angles) else: indx = list(range(0, len(self.snp))) #indx=minConfidence<=self.snp[:,9]<=maxConfidence minsw = self.sw / float(2**self.snp[0, 4]) tsw1 = minsw * 0.5 tsw2 = -minsw * 0.5 * 3**0.5 ntri = len(self.snp) if plotType == 2: fig, ax = plt.subplots() if self.bpatches == False: xy = self.snp[:, :2] tmp = np.asarray([[tsw1] * ntri, (-1)**self.snp[:, 3] * tsw2]).transpose() tris = np.asarray([[[0, 0]] * ntri, [[minsw, 0]] * ntri, tmp]) self.patches = np.swapaxes(tris + xy, 0, 1) self.bpatches = True p = PolyCollection(self.patches[indx], cmap='viridis') p.set_array(self.color2[indx]) p.set_edgecolor('face') ax.add_collection(p) ax.set_xlim([-0.6, 0.6]) ax.set_ylim([-0.6, 0.6]) fig.colorbar(p, ax=ax) plt.show() if plotType == 1: fig, ax = plt.subplots() N = len(self.snp) mat = np.empty([N, 3, 3]) quat = np.empty([N, 4]) rod = np.empty([N, 3]) if self.bcolor1 == False: colors, maxangs, minangs = set_color_range( self, N, indx, mat, quat, rod) self.color1 = colors #print("Color: ", self.color1) #self.bcolor1=True if self.bpatches == False: xy = self.snp[:, :2] tmp = np.asarray([[tsw1] * ntri, (-1)**self.snp[:, 3] * tsw2]).transpose() tris = np.asarray([[[0, 0]] * ntri, [[minsw, 0]] * ntri, tmp]) self.patches = np.swapaxes(tris + xy, 0, 1) self.bpatches = True p = PolyCollection(self.patches[indx], cmap='viridis') p.set_color(self.color1[indx]) ax.add_collection(p) '''Yo future grayson, make sure interactive is a parameter!''' xmin = self.snp[indx[0], 0] xmax = self.snp[indx[0], 0] ymin = self.snp[indx[0], 1] ymax = self.snp[indx[0], 1] for i in indx: if self.snp[i, 0] <= xmin: xmin = self.snp[i, 0] if self.snp[i, 0] >= xmax: xmax = self.snp[i, 0] if self.snp[i, 1] <= ymin: ymin = self.snp[i, 1] if self.snp[i, 1] >= ymax: ymax = self.snp[i, 1] if abs(xmax - xmin) > abs(ymax - ymin): side_length = abs(xmax - xmin) else: side_length = abs(ymax - ymin) ax.set_xlim([xmin - .1, xmin + side_length + .1]) ax.set_ylim([ymin - .1, ymin + side_length + .1]) #note, previously, -.6<=x,y<=.6 voxels = VoxelClick(fig, self.snp, self.sw, self) voxels.connect() print("-------------------------------------------------") print("MaxRod (R,G,B): ", maxangs) print("MinRod (R,G,B): ", minangs) """write line here for adding text next to the plot""" """ maxs = ','.join(str(np.round_(x,decimals=4)) for x in maxangs) mins = ','.join(str(np.round_(x,decimals=4)) for x in minangs) plt.figtext(0.76, 0.5, "mins :"+maxs+"\nmaxes:"+mins) #plt.tight_layout() plt.gcf().subplots_adjust(right=0.75) #adjusting window for text to fit """ plt.show()
0.0029092716847696, 0.00356688706734209, 0.00479077379901016, 0.00685504146621263, 0.0125617481538253, 0.0328812131141895, 0.098875134437398, 0.17861702662974, 0.20581123651118, 0.158502290327443, 0.10979557830891, 0.0433181749174081, 0.0127110651278319, 0.00262555547231493 ] fig = plt.figure() ax = fig.gca(projection='3d') verts = [] for i in range(0, 7): verts.append(list(zip(np.array(ens[i]), np.array(ps[i])))) poly = PolyCollection(verts) poly.set_alpha(0.6) poly.set_linestyle('-') poly.set_edgecolor('k') ax.add_collection3d(poly, zs=angles, zdir='y') maxEn = max(max(ens)) ax.set_ylabel('cosine', fontsize=12) ax.set_ylim3d(-1, 1) ax.set_zlabel('probability/eV', fontsize=12) ax.set_zlim3d(0, 0.25) ax.set_xlabel('energy(Mev)', fontsize=12) ax.set_xlim3d(0.1, maxEn + maxEn * 0.1) plt.savefig(f"spectrum.png", dpi=1200) #plt.show()
polys = [] for i in range(clippedData.GetNumberOfCells()): cell = clippedData.GetCell(i) nPoints = cell.GetNumberOfPoints() points = np.zeros((nPoints, 2)) for pointI in range(nPoints): points[pointI, :] = cell.GetPoints().GetPoint(pointI)[:2] points[pointI, :] /= [scaleX, scaleY] polys.append(points) polyCollection = PolyCollection(polys, **kwargs) if "edgecolor" not in kwargs: polyCollection.set_edgecolor("face") data = np.copy(vtk_to_numpy(clippedData.GetCellData()['temp'])) polyCollection.set_array(data) ax = plt.gca() ax.add_collection(polyCollection) if colorbar: add_colorbar(polyCollection) if plotBoundaries: plot_boundaries(case, scaleX=scaleX, scaleY=scaleY) ax.set_xlim(xlim / scaleX) ax.set_ylim(ylim / scaleY) ax.set_aspect('equal')
def skyhist(ax, ra=None, dec=None, values=None, bins=None, steps=None, max_stepsize=5, edge=1e-6, vmin=None, vmax=None, cmap=mpl.cm.Blues, cblabel=None, **kwargs): """This function in a build-in axes method that makes a sky histogram of the coordinates. Build-in axes method for 2d-histograms of points on the sky. ax: [matplotlib.axes] where the data will be displayed should be using Mollweide or Hammer projection (not strictly enforced) - options - ra, dec: [N array, N array] arrays of sky coordinates (RA, Dec) in degrees values: [N array] array of values for each bin (can be used instead of ra and dec; must number of bins as length) bins [Bins object] object that bins the coordinates and provides the boundaries for drawing polygons (see the documentation of utils/plot/skybins.py) steps [int] number of steps between bin verices (if None, it will be determined based on max_stepsize) max_stepsize [float] maximal stepsize used to determined steps if None edges [float] edge to be left near RA = 180 deg vmin,vmax: [float,float] minimal and maximal values for the colormapping. cmap: [mpl.cm] a colormap cblabel: [string] colorbar label - kwargs goes to matplotlib.collections.PolyCollection - Return ------ collection (output of matplotlib.collections.PolyCollection) cbar (output of ax.colorbar) """ # ----------------------- # - Properties of plot from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection, PolyCollection from .skybins import SkyBins from .skyplot import convert_radec_azel if bins is None: bins = SkyBins() if cblabel is None: cblabel = '' if values is None: values = bins.hist(ra, dec) else: values = np.array(values) patches = [] p_idx = [] for k in range(len(values)): radec_bd = bins.boundary(k, steps=steps, max_stepsize=max_stepsize, edge=edge) for r, d in radec_bd: coord_bd = np.asarray(convert_radec_azel(r, d, edge=edge)).T patches.append(coord_bd) p_idx.append(k) c = np.asarray(values[np.asarray(p_idx)]) vmin = c.min() if vmin is None else vmin vmax = c.max() if vmax is None else vmax color = cmap((c - vmin) / float(vmax - vmin)) collec = PolyCollection(patches, facecolors=color, **kwargs) collec.set_edgecolor('face') # -- Plot ax.add_collection(collec) axcar = ax.insert_ax('bottom', shrunk=0.85, space=0, axspace=0.08) cbar = axcar.colorbar(cmap, vmin=vmin, vmax=vmax, label=cblabel) return collec, cbar
ax3d = fig.add_axes([.57,.22,.38,.38*winAspect], projection='3d') ax3d.set_xlabel('X') ax3d.set_ylabel('Z') # swap Y and Z ax3d.set_zlabel('Y') ax3d.set_xlim3d(-1, 1) ax3d.set_ylim3d(-1, 1) ax3d.set_zlim3d(1, -1) # Back plane verts3D = np.array([[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1],[-1,-1,1]]) vertsXY = [verts3D[:,:2]] vertsZ = verts3D[:,2] poly1 = PolyCollection(vertsXY) poly1.set_alpha(0.7) poly1.set_color('w') poly1.set_edgecolor('k') ax3d.add_collection3d(poly1, zs=vertsZ, zdir='y') # Front plane #verts3D = np.array([[-1,-1,-.95],[1,-1,-.95],[1,1,-.95],[-1,1,-.95],[-1,-1,-.95]]) verts3D = np.array([[-1,-1,-1],[1,-1,-1],[1,1,-1],[-1,1,-1],[-1,-1,-1]]) vertsXY = [verts3D[:,:2]] vertsZ = verts3D[:,2] poly2 = PolyCollection(vertsXY) poly2.set_alpha(0.7) poly2.set_color('w') poly2.set_edgecolor('k') ax3d.add_collection3d(poly2, zs=vertsZ, zdir='y') def updateSliders(val):
def set_edgecolor(self, colors): PolyCollection.set_edgecolor(self, colors) self._edgecolors3d = PolyCollection.get_edgecolor(self)
def swhlocal(swhs, verts, ncels, colrs, config, mdlname='SMC', datx='2018', psfile='output.ps', paprorn='portrait', paprtyp='a3'): ## Import relevant modules and functions import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.collections import PolyCollection from readcell import readtext from colrboxy import colrboxy from scale_swh import scale_swh ## Degree to radian conversion parameter. d2rad = np.pi / 180.0 ## Local plot configuration parameters rdpols = config[0] sztpxy = config[1] rngsxy = config[2] clrbxy = config[3] ## Maximum mapping radius. radius = rdpols[0] ## Set up wave height scale and marks with colrs.N. ## colrs.N returns colrs' total number of colors 256. waveht, factor, residu, marks, ncstr, nclrm = scale_swh(nclrm=colrs.N) resmn1 = residu - 1.0 nswh0 = ncstr + int(factor * np.log(-resmn1 + residu)) # print ' nswh0 and marks = ', nswh0, marks # print ' factor, residu, resmn1 = %f, %f, %f' % (factor, residu, resmn1) ## Some constant variables for plots. xprop = {'xlim': rngsxy[0:2], 'xlabel': ''} yprop = {'ylim': rngsxy[2:4], 'ylabel': ''} ## Use ijk to count how many times to draw. ijk = 0 if True: ## Work out max and min values, excluding missing data (-999.0) cmax = swhs.max() cmin = swhs[swhs > -999.0].min() print(' swh range %f, %f' % (cmin, cmax)) cmxs = 'SWHmx = %6.2f m' % cmax cmns = 'SWHmn = %10.3E' % cmin ## Reset missing values (-999.0) to be -resmn1 swhs[swhs < -resmn1] = -resmn1 ## Trim large values into plot range if any swhs[swhs > 32.0] = 32.0 ## Convert swhs with logarithm scale. icnf = ncstr + np.rint(factor * np.log(swhs + residu)) nswh = np.array(icnf, dtype=np.int16) print(" Drawing " + psfile) ## Set up first subplot and axis for northern hemisphere fig = plt.figure(figsize=sztpxy[0:2]) ax = fig.add_subplot(1, 1, 1) ax.set(**xprop) ax.set(**yprop) ax.set_aspect('equal') ax.set_autoscale_on(False) ax.set_axis_off() plt.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0) ## Prepare PolyCollection for this plot. polynorth = PolyCollection(verts) ## Create color array for this plot pcface = [] pcedge = [] for i in ncels: if (nswh[i] != nswh0): pcface.append(colrs(nswh[i])) pcedge.append(colrs(nswh[i])) else: pcface.append(colrs(255)) pcedge.append(colrs(0)) # smcpoly.set_color(pcolr) ## This line defines both edge and face color. polynorth.set_facecolor(pcface) polynorth.set_edgecolor(pcedge) polynorth.set_linewidth(0.2) # print (" Drawing north hemisphere cells ... ") ax.add_collection(polynorth) ## Draw colorbar inside plot. xkeys, ykeys, clrply = colrboxy(clrbxy, colrs, marks) ax.add_collection(clrply) dkx = clrbxy[2] dky = clrbxy[3] for i in range(len(waveht)): m = marks[i] if (dkx < dky): plt.text(xkeys[0] + 1.15 * dkx, ykeys[m], str(waveht[i]), verticalalignment='center', fontsize=11, color='b') else: plt.text(xkeys[m], ykeys[0] + 1.15 * dky, str(waveht[i]), horizontalalignment='center', fontsize=11, color='b') if (dkx < dky): plt.text(xkeys[0] + 2.0 * dkx, ykeys[marks[3]], 'SWH m', rotation=90, verticalalignment='center', fontsize=15, color='k') else: plt.text(xkeys[marks[3]], ykeys[0] + 2.0 * dky, 'SWH m', rotation=0, horizontalalignment='center', fontsize=15, color='k') ## Put cell information inside plot tpx = sztpxy[2] tpy = sztpxy[3] plt.text(tpx, tpy - 1.0, mdlname, horizontalalignment='center', fontsize=17, color='g') plt.text(tpx, tpy - 1.6, datx, horizontalalignment='center', fontsize=15, color='k') plt.text(tpx, tpy - 2.1, cmxs, horizontalalignment='center', fontsize=13, color='r') plt.text(tpx, tpy - 2.6, cmns, horizontalalignment='center', fontsize=13, color='b') ## Refresh subplots and save them. plt.savefig(psfile, dpi=None, facecolor='w', edgecolor='w', orientation=paprorn, papertype=paprtyp) plt.close()