class VarPlot(object): def __init__(self, var, cmap, axes): self.axes = axes self.var = var self.cmap = cmap self.mesh = self.var.mesh self.plot_mesh() def plot_mesh(self): vertexIDs = self.mesh._orderedCellVertexIDs vertexCoords = self.mesh.vertexCoords xCoords = numerix.take(vertexCoords[0], vertexIDs) yCoords = numerix.take(vertexCoords[1], vertexIDs) polys = [] for x, y in zip(xCoords.swapaxes(0, 1), yCoords.swapaxes(0, 1)): polys.append(zip(x, y)) self.collection = PolyCollection(polys) self.collection.set_linewidth(0.5) self.axes.add_collection(self.collection) self.update(self.var) def update(self, var): rgba = self.cmap(var.value) self.collection.set_facecolors(rgba) self.collection.set_edgecolors(rgba)
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 stockplotter(tickerlist, colorlist, intervalsel): fig = plt.gca(projection='3d') numstocks = len(tickerlist) maxy = 0 miny = 0 verts = getstockslist(tickerlist, intervalsel) for x in range(len(verts)): for y in range(len(verts[x])): if verts[x][y][1] > maxy: maxy = verts[x][y][1] if verts[x][y][1] < miny: miny = verts[x][y][1] customlegend = [] for x in range(numstocks): customlegend.append( mpatches.Patch(color=colorlist[x], label=tickerlist[x].upper())) fig.legend(handles=customlegend) zs = np.arange(0, numstocks, 1.0) poly = PolyCollection(verts, facecolors=colorlist[0:numstocks], lw=0.5, edgecolor=(0, 0, 0, 1)) poly.set_alpha(0.5) poly.set_linestyle(ls='-') poly.set_linewidth(lw=2.0) fig.add_collection3d(poly, zs=zs, zdir='y') if intervalsel == '7d': fig.set_xlim3d(0, 7) fig.set_xlabel("Time (day)") fig.set_zlabel("Price increase since start of week(%)") else: fig.set_xlim3d(0, len(verts[0])) if intervalsel == '1mo': fig.set_xlabel("Time (hr)") fig.set_zlabel("Price increase in last month(%)") if intervalsel == '1y': fig.set_xlabel("Time (day)") fig.set_zlabel("Price increase in last year(%)") #to change when understand fig.set_ylabel("Stock") fig.set_ylim3d(0, numstocks) #set to number of stocks fig.set_zlim3d(miny, maxy) plt.show() plt.close('all')
def plotSolution(self, heatExch, axes, var, zmin=None, zmax=None, cmap=cm.jet): vertexIDs = self.mesh._orderedCellVertexIDs vertexCoords = self.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)) from matplotlib.collections import PolyCollection # Set limits xmin = xCoords.min() xmax = xCoords.max() ymin = yCoords.min() ymax = yCoords.max() axes.set_xlim(xmin=xmin, xmax=xmax) axes.set_ylim(ymin=ymin, ymax=ymax) Z = var.value if (zmin is None): zmin = np.min(Z) if (zmax is None): zmax = np.max(Z) norm = Normalize(zmin, zmax) collection = PolyCollection(polys, cmap=cmap, norm=norm) collection.set_linewidth(0.) axes.add_collection(collection) cbax, _ = colorbar.make_axes(axes) cb = colorbar.ColorbarBase(cbax, cmap=cmap, norm=norm) cb.set_label('Temperature [K]') collection.set_array(np.array(Z))
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 plotSolution(self, heatExch, axes, var, zmin = None, zmax = None, cmap = cm.jet): vertexIDs = self.mesh._orderedCellVertexIDs vertexCoords = self.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)) from matplotlib.collections import PolyCollection # Set limits xmin = xCoords.min() xmax = xCoords.max() ymin = yCoords.min() ymax = yCoords.max() axes.set_xlim(xmin=xmin, xmax=xmax) axes.set_ylim(ymin=ymin, ymax=ymax) Z = var.value if (zmin is None): zmin = np.min(Z) if (zmax is None): zmax = np.max(Z) norm = Normalize(zmin, zmax) collection = PolyCollection(polys, cmap = cmap, norm = norm) collection.set_linewidth(0.) axes.add_collection(collection) cbax, _ = colorbar.make_axes(axes) cb = colorbar.ColorbarBase(cbax, cmap=cmap, norm = norm) cb.set_label('Temperature [K]') collection.set_array(np.array(Z))
class Matplotlib2DViewer(_MatplotlibViewer): """ Displays a contour plot of a 2D `CellVariable` object. The `Matplotlib2DViewer` plots a 2D `CellVariable` using Matplotlib_. .. _Matplotlib: http://matplotlib.sourceforge.net/ """ __doc__ += _MatplotlibViewer._test2Dirregular(viewer="Matplotlib2DViewer") def __init__(self, vars, title=None, limits={}, cmap=None, colorbar=True, axes=None, **kwlimits): """Creates a `Matplotlib2DViewer`. :Parameters: vars a `CellVariable` object. title displayed at the top of the `Viewer` window limits : dict a (deprecated) alternative to limit keyword arguments cmap the colormap. Defaults to `matplotlib.cm.jet` xmin, xmax, ymin, ymax, datamin, datamax displayed range of data. Any limit set to a (default) value of `None` will autoscale. colorbar plot a colorbar in specified orientation if not `None` axes if not `None`, `vars` will be plotted into this Matplotlib `Axes` object """ kwlimits.update(limits) _MatplotlibViewer.__init__(self, vars=vars, title=title, figaspect=1. / 1.3, cmap=cmap, colorbar=colorbar, axes=axes, **kwlimits) self.mesh = self.vars[0].getMesh() vertexIDs = self.mesh._getOrderedCellVertexIDs() vertexCoords = self.mesh.getVertexCoords() xCoords = numerix.take(vertexCoords[0], vertexIDs) yCoords = numerix.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)) import matplotlib from matplotlib.collections import PolyCollection self.collection = PolyCollection(polys) self.collection.set_linewidth(0.5) try: self.axes.add_patch(self.collection) except: # PolyCollection not child of PatchCollection in matplotlib 0.98 self.axes.add_collection(self.collection) xmin = self._getLimit('xmin', default=xCoords.min()) xmax = self._getLimit('xmax', default=xCoords.max()) ymin = self._getLimit('ymin', default=yCoords.min()) ymax = self._getLimit('ymax', default=yCoords.max()) self.axes.set_xlim(xmin=xmin, xmax=xmax) self.axes.set_ylim(ymin=ymin, ymax=ymax) self._plot() def _getSuitableVars(self, vars): from fipy.meshes.numMesh.mesh2D import Mesh2D from fipy.variables.cellVariable import CellVariable vars = [var for var in _MatplotlibViewer._getSuitableVars(self, vars) \ if ((isinstance(var.getMesh(), Mesh2D) and isinstance(var, CellVariable)) and var.getRank() == 0)] if len(vars) == 0: from fipy.viewers import MeshDimensionError raise MeshDimensionError, "Matplotlib2DViewer can only display a rank-0, 2D CellVariable" # this viewer can only display one variable return [vars[0]] def _plot(self): ## pylab.clf() ## ## Added garbage collection since matplotlib objects seem to hang ## ## around and accumulate. ## import gc ## gc.collect() Z = self.vars[0].getValue() zmin, zmax = self._autoscale(vars=self.vars, datamin=self._getLimit(('datamin', 'zmin')), datamax=self._getLimit(('datamax', 'zmax'))) diff = zmax - zmin import matplotlib if diff == 0: rgba = self.cmap(0.5) else: rgba = self.cmap((Z - zmin) / diff) self.collection.set_facecolors(rgba) self.collection.set_edgecolors(rgba) if self.colorbar is not None: self.colorbar.plot(vmin=zmin, vmax=zmax)
class Matplotlib2DViewer(_MatplotlibViewer): """ Displays a contour plot of a 2D `CellVariable` object. The `Matplotlib2DViewer` plots a 2D `CellVariable` using Matplotlib_. .. _Matplotlib: http://matplotlib.sourceforge.net/ """ __doc__ += _MatplotlibViewer._test2Dirregular(viewer="Matplotlib2DViewer") def __init__(self, vars, title=None, limits={}, cmap=None, **kwlimits): """Creates a `Matplotlib2DViewer`. :Parameters: vars a `CellVariable` object. title displayed at the top of the `Viewer` window limits : dict a (deprecated) alternative to limit keyword arguments cmap the colormap. Defaults to `pylab.cm.jet` xmin, xmax, ymin, ymax, datamin, datamax displayed range of data. Any limit set to a (default) value of `None` will autoscale. """ kwlimits.update(limits) _MatplotlibViewer.__init__(self, vars=vars, title=title, figaspect=1. / 1.3, **kwlimits) self.colorbar = None self.mesh = self.vars[0].getMesh() vertexIDs = self.mesh._getOrderedCellVertexIDs() vertexCoords = self.mesh.getVertexCoords() xCoords = numerix.take(vertexCoords[0], vertexIDs) yCoords = numerix.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)) import pylab import matplotlib fig = pylab.figure(self.id) ax = fig.get_axes()[0] from matplotlib.collections import PolyCollection self.collection = PolyCollection(polys) self.collection.set_linewidth(0.5) try: ax.add_patch(self.collection) except: # PolyCollection not child of PatchCollection in matplotlib 0.98 ax.add_collection(self.collection) if self._getLimit('xmin') is None: xmin = xCoords.min() else: xmin = self._getLimit('xmin') if self._getLimit('xmax') is None: xmax = xCoords.max() else: xmax = self._getLimit('xmax') if self._getLimit('ymin') is None: ymin = yCoords.min() else: ymin = self._getLimit('ymin') if self._getLimit('ymax') is None: ymax = yCoords.max() else: ymax = self._getLimit('ymax') pylab.axis((xmin, xmax, ymin, ymax)) cbax, kw = matplotlib.colorbar.make_axes(ax, orientation='vertical') # Set the colormap and norm to correspond to the data for which # the colorbar will be used. if cmap is None: self.cmap = matplotlib.cm.jet else: self.cmap = cmap norm = matplotlib.colors.normalize(vmin=-1, vmax=1) # ColorbarBase derives from ScalarMappable and puts a colorbar # in a specified axes, so it has everything needed for a # standalone colorbar. There are many more kwargs, but the # following gives a basic continuous colorbar with ticks # and labels. self.cb = matplotlib.colorbar.ColorbarBase(cbax, cmap=self.cmap, norm=norm, orientation='vertical') self.cb.set_label(self.vars[0].name) self._plot() def _getSuitableVars(self, vars): from fipy.meshes.numMesh.mesh2D import Mesh2D from fipy.variables.cellVariable import CellVariable vars = [var for var in _MatplotlibViewer._getSuitableVars(self, vars) \ if ((isinstance(var.getMesh(), Mesh2D) and isinstance(var, CellVariable)) and var.getRank() == 0)] if len(vars) == 0: from fipy.viewers import MeshDimensionError raise MeshDimensionError, "Matplotlib2DViewer can only display a rank-0, 2D CellVariable" # this viewer can only display one variable return [vars[0]] def _plot(self): ## pylab.clf() ## ## Added garbage collection since matplotlib objects seem to hang ## ## around and accumulate. ## import gc ## gc.collect() Z = self.vars[0].getValue() zmin, zmax = self._autoscale(vars=self.vars, datamin=self._getLimit(('datamin', 'zmin')), datamax=self._getLimit(('datamax', 'zmax'))) diff = zmax - zmin import matplotlib if diff == 0: rgba = self.cmap(0.5) else: rgba = self.cmap((Z - zmin) / diff) self.collection.set_facecolors(rgba) self.collection.set_edgecolors(rgba) self.cb.norm = matplotlib.colors.normalize(vmin=zmin, vmax=zmax) self.cb.cmap = self.cmap self.cb.draw_all()
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()
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 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 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')
class Matplotlib2DViewer(AbstractMatplotlib2DViewer): """ Displays a contour plot of a 2D `CellVariable` object. The `Matplotlib2DViewer` plots a 2D `CellVariable` using Matplotlib_. .. _Matplotlib: http://matplotlib.sourceforge.net/ """ __doc__ += AbstractMatplotlib2DViewer._test2Dirregular(viewer="Matplotlib2DViewer") def __init__(self, vars, title=None, limits={}, cmap=None, colorbar='vertical', axes=None, figaspect='auto', **kwlimits): """Creates a `Matplotlib2DViewer`. :Parameters: vars a `CellVariable` object. title displayed at the top of the `Viewer` window limits : dict a (deprecated) alternative to limit keyword arguments cmap the colormap. Defaults to `matplotlib.cm.jet` xmin, xmax, ymin, ymax, datamin, datamax displayed range of data. Any limit set to a (default) value of `None` will autoscale. colorbar plot a colorbar in specified orientation if not `None` axes if not `None`, `vars` will be plotted into this Matplotlib `Axes` object figaspect desired aspect ratio of figure. If arg is a number, use that aspect ratio. If arg is 'auto', the aspect ratio will be determined from the Variable's mesh. """ kwlimits.update(limits) AbstractMatplotlib2DViewer.__init__(self, vars=vars, title=title, figaspect=figaspect, cmap=cmap, colorbar=colorbar, axes=axes, **kwlimits) self.mesh = self.vars[0].mesh vertexIDs = self.mesh._orderedCellVertexIDs vertexCoords = self.mesh.vertexCoords xCoords = numerix.take(vertexCoords[0], vertexIDs) yCoords = numerix.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(list(zip(x, y))) from matplotlib.collections import PolyCollection self.collection = PolyCollection(polys) self.collection.set_linewidth(0.5) try: self.axes.add_patch(self.collection) except: # PolyCollection not child of PatchCollection in matplotlib 0.98 self.axes.add_collection(self.collection) xmin = self._getLimit('xmin', default=xCoords.min()) xmax = self._getLimit('xmax', default=xCoords.max()) ymin = self._getLimit('ymin', default=yCoords.min()) ymax = self._getLimit('ymax', default=yCoords.max()) self.axes.set_xlim(xmin=xmin, xmax=xmax) self.axes.set_ylim(ymin=ymin, ymax=ymax) self._plot() def _getSuitableVars(self, vars): from fipy.meshes.mesh2D import Mesh2D from fipy.variables.cellVariable import CellVariable vars = [var for var in AbstractMatplotlib2DViewer._getSuitableVars(self, vars) \ if ((var.mesh.dim == 2 and isinstance(var, CellVariable)) and var.rank == 0)] if len(vars) == 0: from fipy.viewers import MeshDimensionError raise MeshDimensionError("Matplotlib2DViewer can only display a rank-0, 2D CellVariable") # this viewer can only display one variable return [vars[0]] def _plot(self): ## plt.clf() ## ## Added garbage collection since matplotlib objects seem to hang ## ## around and accumulate. ## import gc ## gc.collect() Z = self.vars[0].value self.norm.vmin = self._getLimit(('datamin', 'zmin')) self.norm.vmax = self._getLimit(('datamax', 'zmax')) rgba = self.cmap(self.norm(Z)) self.collection.set_facecolors(rgba) self.collection.set_edgecolors(rgba) if self.colorbar is not None: self.colorbar.plot() #vmin=zmin, vmax=zmax)
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()
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() print ax.get_xticklabels()
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
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()
class Matplotlib2DViewer(AbstractMatplotlib2DViewer): """ Displays a contour plot of a 2D `CellVariable` object. The `Matplotlib2DViewer` plots a 2D `CellVariable` using Matplotlib_. .. _Matplotlib: http://matplotlib.sourceforge.net/ """ __doc__ += AbstractMatplotlib2DViewer._test2Dirregular( viewer="Matplotlib2DViewer") def __init__(self, vars, title=None, limits={}, cmap=None, colorbar='vertical', axes=None, figaspect='auto', **kwlimits): """Creates a `Matplotlib2DViewer`. :Parameters: vars a `CellVariable` object. title displayed at the top of the `Viewer` window limits : dict a (deprecated) alternative to limit keyword arguments cmap the colormap. Defaults to `matplotlib.cm.jet` xmin, xmax, ymin, ymax, datamin, datamax displayed range of data. Any limit set to a (default) value of `None` will autoscale. colorbar plot a colorbar in specified orientation if not `None` axes if not `None`, `vars` will be plotted into this Matplotlib `Axes` object figaspect desired aspect ratio of figure. If arg is a number, use that aspect ratio. If arg is 'auto', the aspect ratio will be determined from the Variable's mesh. """ kwlimits.update(limits) AbstractMatplotlib2DViewer.__init__(self, vars=vars, title=title, figaspect=figaspect, cmap=cmap, colorbar=colorbar, axes=axes, **kwlimits) self.mesh = self.vars[0].mesh vertexIDs = self.mesh._orderedCellVertexIDs vertexCoords = self.mesh.vertexCoords xCoords = numerix.take(vertexCoords[0], vertexIDs) yCoords = numerix.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(list(zip(x, y))) from matplotlib.collections import PolyCollection self.collection = PolyCollection(polys) self.collection.set_linewidth(0.5) try: self.axes.add_patch(self.collection) except: # PolyCollection not child of PatchCollection in matplotlib 0.98 self.axes.add_collection(self.collection) xmin = self._getLimit('xmin', default=xCoords.min()) xmax = self._getLimit('xmax', default=xCoords.max()) ymin = self._getLimit('ymin', default=yCoords.min()) ymax = self._getLimit('ymax', default=yCoords.max()) self.axes.set_xlim(xmin=xmin, xmax=xmax) self.axes.set_ylim(ymin=ymin, ymax=ymax) self._plot() def _getSuitableVars(self, vars): from fipy.meshes.mesh2D import Mesh2D from fipy.variables.cellVariable import CellVariable vars = [var for var in AbstractMatplotlib2DViewer._getSuitableVars(self, vars) \ if ((var.mesh.dim == 2 and isinstance(var, CellVariable)) and var.rank == 0)] if len(vars) == 0: from fipy.viewers import MeshDimensionError raise MeshDimensionError( "Matplotlib2DViewer can only display a rank-0, 2D CellVariable" ) # this viewer can only display one variable return [vars[0]] def _plot(self): ## pylab.clf() ## ## Added garbage collection since matplotlib objects seem to hang ## ## around and accumulate. ## import gc ## gc.collect() Z = self.vars[0].value self.norm.vmin = self._getLimit(('datamin', 'zmin')) self.norm.vmax = self._getLimit(('datamax', 'zmax')) rgba = self.cmap(self.norm(Z)) self.collection.set_facecolors(rgba) self.collection.set_edgecolors(rgba) if self.colorbar is not None: self.colorbar.plot() #vmin=zmin, vmax=zmax)
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. ... Arguments --------- 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