def animate(p): global count, centers, angles, coords, skip, colors, histogram, success, angle_histogram mc() density = histogram/leny/dx/count xnew, density = make_square(xcoords, density) line.set_ydata(density) ang_vals = angle_histogram/count/pi ax3.collections = [] angplot = ax3.pcolormesh(x, theta, ang_vals, vmin=0, vmax=.01, edgecolors='face', cmap=cm.hot_r) #angplot = ax3.contourf(x, theta, ang_vals, levels=arange(0, .0105, .001), extend="max", rasterized=True) cbar_ax.collections = [] cs = fig.colorbar(angplot, cax=cbar_ax, ticks=[]) cs.cmap.set_over('k') cs.set_clim([0, .01]) ax2.set_ylim(0, 0.8) for i in xrange(n): coords[i] = verts(centers[i], angles[i]) coll = PolyCollection(coords) colors = zeros(n) + cdefault colors[0] = cspecial coll.set_color([cm.jet(val) for val in colors]) ax.collections=[] ax.add_collection(coll) ax.set_title("Attempted: %6i, Successful: %6i" %(count*n, success)) #fig.tight_layout() print p return line, ax2, ax3
def poly3d(df, elev=0, azim=0, **pltkwds): ''' Written by evelyn, updated by Adam 12/1/12.''' xlabel, ylabel, title, pltkwds=pu.smart_label(df, pltkwds) zlabel_def='' zlabel=pltkwds.pop('zlabel', zlabel_def) zs=df.columns verts=[zip(df.index, df[col]) for col in df] #don't have to say df.columns fig = plt.figure() ax = fig.gca(projection='3d') ### Convert verts(type:list) to poly(type:mpl_toolkits.mplot3d.art3d.Poly3DCollection) ### poly used in plotting function ax.add_collection3d to do polygon plot cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6) poly = PolyCollection((verts), facecolors = [cc('b'), cc('g'), cc('r'), cc('y'),cc('m'), cc('c'), cc('b'),cc('g'),cc('r'), cc('y')]) poly.set_alpha(0.2) ### zdir is the direction used to plot,here we use time so y axis ax.add_collection3d(poly, zs=zs, zdir='x') ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) #Y ax.set_zlabel(zlabel) #data ax.set_title(title) ax.set_ylim3d(min(df.index), max(df.index)) ax.set_xlim3d(min(df.columns), max(df.columns)) #x ax.set_zlim3d(min(df.min()), max(df.max())) #How to get absolute min/max of df values ax.view_init(elev, azim) return ax
def index_bar(ax, vals, facecolor='b', edgecolor='l', width=4, alpha=1.0, ): """ Add a bar collection graph with height vals (-1 is missing). ax : an Axes instance to plot to width : the bar width in points alpha : bar transparency """ facecolors = (colorConverter.to_rgba(facecolor, alpha),) edgecolors = (colorConverter.to_rgba(edgecolor, alpha),) right = width/2.0 left = -width/2.0 bars = [ ( (left, 0), (left, v), (right, v), (right, 0)) for v in vals if v != -1 ] sx = ax.figure.dpi * (1.0/72.0) # scale for points sy = ax.bbox.height / ax.viewLim.height barTransform = Affine2D().scale(sx,sy) offsetsBars = [ (i, 0) for i,v in enumerate(vals) if v != -1 ] barCollection = PolyCollection(bars, facecolors = facecolors, edgecolors = edgecolors, antialiaseds = (0,), linewidths = (0.5,), offsets = offsetsBars, transOffset = ax.transData, ) barCollection.set_transform(barTransform) minpy, maxx = (0, len(offsetsBars)) miny = 0 maxy = max([v for v in vals if v!=-1]) corners = (minpy, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() ax.add_collection(barCollection) return barCollection
def funDisplayDifferenceCurveIn3D(vecDigitLevel, inputData_x, dataToDisplay_y, xLabelText, yLabelText, zLabelText, titleText, figureName): ''' Exactly the same as the function above, but in 3D, yes in 3D, it is the future here. ''' fig = plt.figure() ax = fig.gca(projection='3d') cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.2) xs = inputData_x verts = [] tabColor = [] zs = vecDigitLevel for ii in np.arange(0,np.size(vecDigitLevel)): ys = dataToDisplay_y[ii,:] ys[0], ys[-1] = 0, 0 verts.append(list(zip(xs, ys))) tabColor.append(list(cc(repr(vecDigitLevel[ii]/255.)))) poly = PolyCollection(verts, facecolors = tabColor) poly.set_alpha(0.7) ax.add_collection3d(poly, zs=zs, zdir='y') ax.set_xlabel(xLabelText)#'level search') ax.set_xlim3d(0, 255) ax.set_ylabel(yLabelText)#'level tested') ax.set_ylim3d(-1, 256) ax.set_zlabel(zLabelText)#L difference') ax.set_zlim3d(0, 1) plt.title(titleText)#'Various difference curves in 3D') plt.draw() plt.savefig(figureName)# dirToSaveResults+prefixName+'_c1_2.png')
def __init__(self, ax, *args, **kw): self.ax = ax X, Y, U, V, C = self._parse_args(*args) self.X = X self.Y = Y self.N = len(X) self.scale = kw.pop('scale', None) self.headwidth = kw.pop('headwidth', 3) self.headlength = float(kw.pop('headlength', 5)) self.headaxislength = kw.pop('headaxislength', 4.5) self.minshaft = kw.pop('minshaft', 1) self.minlength = kw.pop('minlength', 1) self.units = kw.pop('units', 'width') self.width = kw.pop('width', None) self.color = kw.pop('color', 'k') self.pivot = kw.pop('pivot', 'tail') kw.setdefault('facecolors', self.color) kw.setdefault('linewidths', (0,)) PolyCollection.__init__(self, None, offsets=zip(X, Y), transOffset=ax.transData, **kw) self.polykw = kw self.set_UVC(U, V, C) self._initialized = False self.keyvec = None self.keytext = None
def make_image(x): ''' x wil be a matrix data structure. ''' fig = plt.figure() ax = fig.gca(projection='3d') # cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6) # xs = np.arange(0, 10, 0.4) verts = x.get_verts('freq') for i in xrange(17): print verts[0][i],'\n' for i in xrange(17): print verts[1][i],'\n' zs = [0.0, 1.0, 2.0, 3.0] # for z in zs: # ys = np.random.rand(len(xs)) # ys[0], ys[-1] = 0, 0 # verts.append(list(zip(xs, ys))) # poly = PolyCollection(verts, facecolors = [cc('r'), cc('g'), cc('b'),cc('y')]) poly = PolyCollection(verts) poly.set_alpha(0.3) # ax.add_collection3d(poly, zs=zs, zdir='y') ax.add_collection3d(poly, zs=zs, zdir='y') # ax.set_xlabel('X') ax.set_xlim3d(0, 123456) ax.set_ylabel('Y') ax.set_ylim3d(0, 65536) ax.set_zlabel('Z') ax.set_zlim3d(0, 1000) # plt.show()
def plotPolyArrayFunction(self,result): interval = ((self.endValue - self.startValue) / (self.polyNumber - 1)) self.rr.reset() fig = plt.figure() ax = fig.gca(projection='3d') if self.startValue is None: self.startValue = self.rr.model[self.value] columnNumber = self.polyNumber + 1 lastPoint = [self.endTime] firstPoint = [self.startTime] for i in range(int(columnNumber) - 1): lastPoint.append(0) firstPoint.append(0) lastPoint = np.array(lastPoint) firstPoint = np.array(firstPoint) zresult = np.vstack((result, lastPoint)) zresult = np.vstack((firstPoint, zresult)) zs = [] result = [] for i in range(int(columnNumber) - 1): zs.append(i) result.append(zip(zresult[:, 0], zresult[:, (i + 1)])) if self.color is None: poly = PolyCollection(result) else: if len(self.color) != self.polyNumber: self.color = self.colorCycle() poly = PolyCollection(result, facecolors=self.color, closed=False) poly.set_alpha(self.alpha) ax.add_collection3d(poly, zs=zs, zdir='y') ax.set_xlim3d(0, self.endTime) ax.set_ylim3d(0, (columnNumber - 1)) ax.set_zlim3d(0, (self.endValue + interval)) if self.xlabel == 'toSet': ax.set_xlabel('Time') elif self.xlabel: ax.set_xlabel(self.xlabel) if self.ylabel == 'toSet': ax.set_ylabel('Trial Number') elif self.ylabel: ax.set_ylabel(self.ylabel) if self.zlabel == 'toSet': ax.set_zlabel(self.value) elif self.zlabel: ax.set_zlabel(self.zlabel) # ax.set_xlabel('Time') if self.xlabel is None else ax.set_xlabel(self.xlabel) # ax.set_ylabel('Trial Number') if self.ylabel is None else ax.set_ylabel(self.ylabel) # ax.set_zlabel(self.value) if self.zlabel is None else ax.set_zlabel(self.zlabel) if self.title is not None: ax.set_title(self.title) if not IPYTHON: plt.show() else: FILENAME = str(uuid.uuid4()) + ".png" plt.savefig(FILENAME) plt.close() imag = mpimg.imread(FILENAME) return(imag)
def draw(self, renderer): self._init() if self._new_UV: verts = self._make_verts(self.U, self.V) self.set_verts(verts) self._new_UV = False PolyCollection.draw(self, renderer)
def visualizeHealPixMap(theMap, nest=True, title="map", norm=None, vmin=None, vmax=None, cmap=plt.cm.hot_r): from matplotlib.collections import PolyCollection from matplotlib.colors import Normalize nside = hp.npix2nside(theMap.size) mapValue = theMap[theMap != hp.UNSEEN] indices = np.arange(theMap.size) seenInds = indices[theMap != hp.UNSEEN] print "Building polygons from HEALPixel map." vertices = np.zeros( (seenInds.size, 4, 2) ) print "Building polygons for "+str(seenInds.size)+" HEALPixels." for HPixel,i in zip(seenInds,xrange(seenInds.size)): corners = hp.vec2ang( np.transpose(hp.boundaries(nside,HPixel,nest=nest) ) ) # HEALPix insists on using theta/phi; we in astronomy like to use ra/dec. vertices[i,:,0] = corners[1] *180./np.pi vertices[i,:,1] = 90.0 - corners[0] * 180/np.pi fig, ax = plt.subplots(figsize=(12,12)) #coll = PolyCollection(vertices, array = mapValue, cmap = plt.cm.seismic, edgecolors='none') coll = PolyCollection(vertices, array=mapValue, cmap=cmap, edgecolors='none') coll.set_clim(vmin=vmin, vmax=vmax) ax.add_collection(coll) ax.set_title(title) ax.autoscale_view() fig.colorbar(coll,ax=ax) #ax.set_ylim([-60.2, -43]) print "Writing to file: "+title+".png" fig.savefig(title+".png",format="png")
def __init__(self, start_ls, end_ls, y=0, width=0.001, x_offset=0, is_arrow=True, length_includes_head=True, \ head_width=None, head_length=None, shape='full', overhang=0, \ head_starts_at_zero=False,**kwargs): if head_width is None: head_width = 2 * width if head_length is None: head_length = 1/(2.0 * abs(end_ls[0]-start_ls[0])) distance = abs(end_ls[-1]-start_ls[0]) if length_includes_head: length=distance else: length=distance+head_length no_of_blocks = len(start_ls) if not distance: verts_ls = [] #display nothing if empty else: """ start by drawing horizontal arrow, point (tip of the arrow) at (0,0). the whole arrow sticks on the x-axis (<=0 part) Notice: the XY -coordination is not the usual math coordination system. it's canvas coordination. (0,0) is top left. horizontal is y-axis. vertical is x-axis. start from the last block, reversely to the 1st block """ verts_ls = [] for i in range(no_of_blocks): block_start = start_ls[i] block_end = end_ls[i] verts = [[block_start, width/2.0+y], [block_start, -width/2.0+y], [block_end, -width/2.0+y], [block_end, width/2.0+y]] verts_ls.append(verts) PolyCollection.__init__(self, verts_ls, **kwargs)
def plot_series(time, variable, series, ylabel='Y', zlabel='Z', fromzero=False): figure = plt.figure() ax = figure.gca(projection='3d') globalmin = np.min(map(lambda trial: np.min(trial), series)) globalmax = np.max(map(lambda trial: np.max(trial), series)) def stub(trial): if not fromzero: trial = map(lambda x: x - globalmin, np.array(trial)) trial[0] = 0 trial[-1] = 0 return np.array(trial) verts = map(lambda trial: zip(time, stub(trial)), series) poly = PolyCollection(np.array(verts), facecolors=map(lambda n: cm.jet(n), np.linspace(0, 1, len(series)))) poly.set_alpha(0.7) if not fromzero: globalmax -= globalmin globalmin -= globalmin ax.add_collection3d(poly, zs=variable, zdir='y') ax.set_xlim3d(time[0], time[-1]) ax.set_ylim3d(min(variable), max(variable)) ax.set_zlim3d(globalmin, globalmax) ax.set_xlabel('Time (ms)') ax.set_ylabel(ylabel) ax.set_zlabel(zlabel)
def plot4MainDir(degVector): fourDirVector = allDeg24Directions(degVector['Value']) pHours = 24 # periodo considerado sampling = 60 # 10min de amostragem base = pHours*60/sampling totDays = len(fourDirVector)/base # Dias multiplo de 5, para graficos poly 3d days = np.arange(totDays)+1 hours = np.arange(0,pHours*60,sampling) meshTime, indices = np.meshgrid(hours, days) meshProfile = np.zeros(meshTime.shape) profileList = [] ii = 1 for i in range(totDays): dataPeriod = fourDirVector[i*base:ii*base] profileList.append( dataPeriod ) ii +=1 profileMatrix = np.array(profileList) for i in range( indices.shape[0] ): for j in range( indices.shape[1] ): meshProfile[(i,j)] = profileMatrix[(i,j)] fig = plt.figure() ax = fig.gca(projection='3d') X = meshTime Y = indices Z = meshProfile ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='coolwarm', alpha=0.8) # ou a linha abaixo ax.set_xlabel('minutos') ax.set_ylabel('dia') ax.set_zlabel(r'$^oC$') # Visao apenas dos perfis fig2 = plt.figure() ax2 = fig2.gca(projection='3d') cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6) verts = [] cs = [cc('r'), cc('g'), cc('b'), cc('y'), cc('c')]*(totDays/5) k = 0 for d in days: verts.append(list(zip(hours, meshProfile[k]))) k += 1 poly = PolyCollection(verts, facecolors = cs) poly.set_alpha(0.7) ax2.add_collection3d(poly, zs=days, zdir='y') """ OK! Mostra grafico de barras cs = ['r', 'g', 'b', 'y','c']*(totDays/5) k = 0 for c, d in zip(cs, days): cc = [c]*len(hours) ax2.bar(hours, meshProfile[k], zs=d, zdir='y', color=cc, alpha=0.5) k += 1 """ ax2.set_xlabel('minutos') ax2.set_xlim3d(0, hours[-1]) ax2.set_ylabel('dia') ax2.set_ylim3d(0, days[-1]) ax2.set_zlabel('Dir') ax2.set_zlim3d(0, 360) plt.show()
def test_something(self): fig = plt.figure() ax = fig.gca(projection='3d') cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6) xs = np.arange(0, 10, 0.4) verts = [] zs = [0.0, 1.0, 2.0, 3.0] for z in zs: ys = np.random.rand(len(xs)) ys[0], ys[-1] = 0, 0 verts.append(list(zip(xs, ys))) poly = PolyCollection(verts, facecolors = [cc('r'), cc('g'), cc('b'), cc('y')]) poly.set_alpha(0.7) ax.add_collection3d(poly, zs=zs, zdir='y') ax.set_xlabel('Coordinate') ax.set_xlim3d(0, 10) ax.set_ylabel('hypothesis#') ax.set_ylim3d(-1, 4) ax.set_zlabel('Concentration') ax.set_zlim3d(0, 1) plt.show()
def init(self, view): cube_points = np.arange(0, 10, 0.4) verts = [] # number of polygons figures_num = [0.0, 1.0, 2.0, 3.0] for z in figures_num: ys = np.random.rand(len(cube_points)) ys[0], ys[-1] = 0, 0 verts.append(list(zip(cube_points, ys))) poly = PolyCollection(verts, facecolors=[self.convert_color('r'), self.convert_color('g'), self.convert_color('b'), self.convert_color('y')]) poly.set_alpha(0.7) self.ax.add_collection3d(poly, zs=figures_num, zdir='y') self.ax.set_xlabel('X') self.ax.set_xlim3d(0, 10) self.ax.set_ylabel('Y') self.ax.set_ylim3d(-1, 4) self.ax.set_zlabel('Z') self.ax.set_zlim3d(0, 1) if view == "image": savefig('polygon.png') print "Image saved on tredify folder" else: plt.show()
def do_3d_projection(self, renderer): """ Perform the 3D projection for this object. """ # FIXME: This may no longer be needed? if self._A is not None: self.update_scalarmappable() self._facecolors3d = self._facecolors txs, tys, tzs = proj3d.proj_transform_vec(self._vec, renderer.M) xyzlist = [(txs[si:ei], tys[si:ei], tzs[si:ei]) for si, ei in self._segis] # This extra fuss is to re-order face / edge colors cface = self._facecolors3d cedge = self._edgecolors3d if len(cface) != len(xyzlist): cface = cface.repeat(len(xyzlist), axis=0) if len(cedge) != len(xyzlist): if len(cedge) == 0: cedge = cface else: cedge = cedge.repeat(len(xyzlist), axis=0) # if required sort by depth (furthest drawn first) if self._zsort: z_segments_2d = sorted( ((self._zsortfunc(zs), np.column_stack([xs, ys]), fc, ec, idx) for idx, ((xs, ys, zs), fc, ec) in enumerate(zip(xyzlist, cface, cedge))), key=lambda x: x[0], reverse=True) else: raise ValueError("whoops") segments_2d = [s for z, s, fc, ec, idx in z_segments_2d] if self._codes3d is not None: codes = [self._codes3d[idx] for z, s, fc, ec, idx in z_segments_2d] PolyCollection.set_verts_and_codes(self, segments_2d, codes) else: PolyCollection.set_verts(self, segments_2d, self._closed) self._facecolors2d = [fc for z, s, fc, ec, idx in z_segments_2d] if len(self._edgecolors3d) == len(cface): self._edgecolors2d = [ec for z, s, fc, ec, idx in z_segments_2d] else: self._edgecolors2d = self._edgecolors3d # Return zorder value if self._sort_zpos is not None: zvec = np.array([[0], [0], [self._sort_zpos], [1]]) ztrans = proj3d.proj_transform_vec(zvec, renderer.M) return ztrans[2][0] elif tzs.size > 0 : # FIXME: Some results still don't look quite right. # In particular, examine contourf3d_demo2.py # with az = -54 and elev = -45. return np.min(tzs) else : return np.nan
def set_3d_properties(self): # Force the collection to initialize the face and edgecolors # just in case it is a scalarmappable with a colormap. self.update_scalarmappable() self._sort_zpos = None self.set_zsort(True) self._facecolors3d = PolyCollection.get_facecolors(self) self._edgecolors3d = PolyCollection.get_edgecolors(self)
def multidraw(courbesA,courbesB): fig = plt.figure() ax = fig.gca(projection='3d') verts = [] facecolor=[] for lacourbe in courbesA: xs=[] closepoly=[] for idx,X in enumerate(lacourbe): xs.append(idx) closepoly.append(0) xs.append(idx) closepoly.append(X) xs.append(idx+.3) closepoly.append(X) xs.append(idx+.3) closepoly.append(0) xs.append(0) closepoly.append(0) verts.append(list(zip(xs, closepoly))) facecolor.append(cc('b')) for lacourbe in courbesB: xs=[] closepoly=[] for idx,X in enumerate(lacourbe): xs.append(idx) closepoly.append(0) xs.append(idx) closepoly.append(X) xs.append(idx+.3) closepoly.append(X) xs.append(idx+.3) closepoly.append(0) xs.append(0) closepoly.append(0) verts.append(list(zip(xs, closepoly))) facecolor.append(cc('y')) print len(facecolor) ,len(verts) poly = PolyCollection(verts, facecolors=facecolor) zs = range(0,len(facecolor)) poly.set_alpha(0.7) ax.add_collection3d(poly, zs=zs, zdir='y') ax.set_xlabel('X') ax.set_xlim3d(0,5) ax.set_ylabel('Y') ax.set_ylim3d(-1, len(verts)) ax.set_zlabel('Z') ax.set_zlim3d(-3, 3) plt.show()
def set_data(self, zname, zdata, zcolor): if zdata!=None: if zname not in self.clts: #plottables['plotted']:#self.pd.list_data(): clt=PolyCollection(zdata, alpha=0.5, antialiased=True)#, rasterized=False, antialiased=False) clt.set_color(colorConverter.to_rgba(zcolor)) self.clts[zname]=clt self.axe.add_collection(self.clts[zname], autolim=True) else: self.clts[zname].set_verts(zdata)
def poly_plot(self, zname, zdata, zcolor=None): if zname not in self.clts: clt=PolyCollection(zdata, alpha=0.5, antialiased=True) if zcolor is not None: clt.set_color(zcolor) #colorConverter.to_rgba(zcolor)) self.clts[zname]=clt self.axe.add_collection(self.clts[zname]) else: self.clts[zname].set_verts(zdata)
def plotPolyArray(self): """Plots results as individual graphs parallel to each other in 3D space using results from graduatedSim(). p.plotPolyArray()""" result = self.graduatedSim() interval = (self.endValue - self.startValue) / (self.polyNumber - 1) self.rr.reset() fig = plt.figure() ax = fig.gca(projection="3d") if self.startValue is None: self.startValue = self.rr.model[self.value] columnNumber = self.polyNumber + 1 lastPoint = [self.endTime] firstPoint = [self.startTime] for i in range(int(columnNumber) - 1): lastPoint.append(0) firstPoint.append(0) lastPoint = np.array(lastPoint) firstPoint = np.array(firstPoint) zresult = np.vstack((result, lastPoint)) zresult = np.vstack((firstPoint, zresult)) zs = [] result = [] for i in range(int(columnNumber) - 1): zs.append(i) result.append(zip(zresult[:, 0], zresult[:, (i + 1)])) if self.color is None: poly = PolyCollection(result) else: if len(self.color) != self.polyNumber: self.color = self.colorCycle() poly = PolyCollection(result, facecolors=self.color, closed=False) poly.set_alpha(self.alpha) ax.add_collection3d(poly, zs=zs, zdir="y") ax.set_xlim3d(0, self.endTime) ax.set_ylim3d(0, (columnNumber - 1)) ax.set_zlim3d(0, (self.endValue + interval)) if self.xlabel == "toSet": ax.set_xlabel("Time") elif self.xlabel: ax.set_xlabel(self.xlabel) if self.ylabel == "toSet": ax.set_ylabel("Trial Number") elif self.ylabel: ax.set_ylabel(self.ylabel) if self.zlabel == "toSet": ax.set_zlabel(self.value) elif self.zlabel: ax.set_zlabel(self.zlabel) # ax.set_xlabel('Time') if self.xlabel is None else ax.set_xlabel(self.xlabel) # ax.set_ylabel('Trial Number') if self.ylabel is None else ax.set_ylabel(self.ylabel) # ax.set_zlabel(self.value) if self.zlabel is None else ax.set_zlabel(self.zlabel) if self.title is not None: ax.set_title(self.title) plt.show()
def __init__(self, verts, *args, **kwargs): ''' Create a Poly3DCollection. *verts* should contain 3D coordinates. Note that this class does a bit of magic with the _facecolors and _edgecolors properties. ''' PolyCollection.__init__(self, verts, *args, **kwargs) self._zsort = 1 self._sort_zpos = None
def map_poly_shp(shp, which='all', bbox=None): ''' Create a map object from a polygon shape ... Arguments --------- shp : iterable PySAL polygon iterable (e.g. shape object from `ps.open` a poly shapefile) If it does not contain the attribute `bbox`, it must be passed separately in `bbox`. which : str/list List of booleans for which polygons of the shapefile to be included (True) or excluded (False) bbox : None/list [Optional. Default=None] List with bounding box as in a PySAL object. If nothing is passed, it tries to obtain it as an attribute from `shp`. Returns ------- map : PatchCollection Map object with the polygons from the shape This includes the attribute `shp2dbf_row` with the cardinality of every polygon to its row in the dbf (zero-offset) ''' if not bbox: bbox = shp.bbox patches = [] rows = [] i = 0 if which == 'all': for shape in shp: for ring in shape.parts: xy = np.array(ring) patches.append(xy) rows.append(i) i += 1 else: for inwhich, shape in zip(which, shp): if inwhich: for ring in shape.parts: xy = np.array(ring) patches.append(xy) rows.append(i) i += 1 pc = PolyCollection(patches) _ = _add_axes2col(pc, bbox) pc.shp2dbf_row = rows return pc
def volume_overlay(ax, opens, closes, volumes, colorup="k", colordown="r", width=4, alpha=1.0): """ Add a volume overlay to the current axes. The opens and closes are used to determine the color of the bar. -1 is missing. If a value is missing on one it must be missing on all ax : an Axes instance to plot to width : the bar width in points colorup : the color of the lines where close >= open colordown : the color of the lines where close < open alpha : bar transparency """ r, g, b = colorConverter.to_rgb(colorup) colorup = r, g, b, alpha r, g, b = colorConverter.to_rgb(colordown) colordown = r, g, b, alpha colord = {True: colorup, False: colordown} colors = [colord[open < close] for open, close in zip(opens, closes) if open != -1 and close != -1] right = width / 2.0 left = -width / 2.0 bars = [((left, 0), (left, v), (right, v), (right, 0)) for v in volumes if v != -1] sx = ax.figure.dpi * (1.0 / 72.0) # scale for points sy = (ax.bbox.ur().y() - ax.bbox.ll().y()) / (ax.viewLim.ur().y() - ax.viewLim.ll().y()) barTransform = Affine2D().scaled(sx, sy) offsetsBars = [(i, 0) for i, v in enumerate(volumes) if v != -1] barCollection = PolyCollection( bars, facecolors=colors, edgecolors=((0, 0, 0, 1),), antialiaseds=(0,), linewidths=(0.5,), offsets=offsetsBars, transOffset=ax.transData, ) barCollection.set_transform(barTransform) minpy, maxx = (0, len(offsetsBars)) miny = 0 maxy = max([v for v in volumes if v != -1]) corners = (minpy, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() # add these last return barCollection
def do_3d_projection(self, renderer): ''' Perform the 3D projection for this object. ''' # FIXME: This may no longer be needed? if self._A is not None: self.update_scalarmappable() self._facecolors3d = self._facecolors txs, tys, tzs = proj3d.proj_transform_vec(self._vec, renderer.M) xyzlist = [(txs[si:ei], tys[si:ei], tzs[si:ei]) \ for si, ei in self._segis] # This extra fuss is to re-order face / edge colors cface = self._facecolors3d cedge = self._edgecolors3d if len(cface) != len(xyzlist): cface = cface.repeat(len(xyzlist), axis=0) if len(cedge) != len(xyzlist): if len(cedge) == 0: cedge = cface cedge = cedge.repeat(len(xyzlist), axis=0) # if required sort by depth (furthest drawn first) if self._zsort: z_segments_2d = [(self._zsortfunc(zs), zip(xs, ys), fc, ec) for (xs, ys, zs), fc, ec in zip(xyzlist, cface, cedge)] z_segments_2d.sort(cmp=lambda x, y: cmp(y[0], x[0])) else: raise ValueError, "whoops" segments_2d = [s for z, s, fc, ec in z_segments_2d] PolyCollection.set_verts(self, segments_2d) self._facecolors2d = [fc for z, s, fc, ec in z_segments_2d] if len(self._edgecolors3d) == len(cface): self._edgecolors2d = [ec for z, s, fc, ec in z_segments_2d] else: self._edgecolors2d = self._edgecolors3d # Return zorder value if self._sort_zpos is not None: zvec = np.array([[0], [0], [self._sort_zpos], [1]]) ztrans = proj3d.proj_transform_vec(zvec, renderer.M) return ztrans[2][0] elif tzs.size > 0 : # FIXME: Some results still don't look quite right. # In particular, examine contourf3d_demo2.py # with az = -54 and elev = -45. return np.min(tzs) else : return np.nan
def plot(): fig = plt.figure() axis = fig.add_subplot(1, 1, 1) col = PolyCollection( [], facecolors="none", edgecolors="red", linestyle="--", linewidth=1.2 ) col.set_zorder(1) axis.add_collection(col) axis.set_xlim(0.5, 2.5) axis.set_ylim(0.5, 2.5) axis.collections[0].set_verts([[[1, 1], [1, 2], [2, 2], [2, 1]]]) return fig
def plot_energy_3d(name, key_steps=50, filename=None): data = np.loadtxt('%s_energy.ndt' % name) if data.ndim == 1: data.shape = (1, -1) fig = plt.figure() ax = fig.gca(projection='3d') # image index xs = range(1, data.shape[1]) steps = data[:, 0] each_n_step = int(len(steps) / key_steps) if each_n_step < 1: each_n_step = 1 cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6) colors = [cc('r'), cc('g'), cc('b'), cc('y')] facecolors = [] line_data = [] energy_min = np.min(data[:, 1:]) zs = [] index = 0 for i in range(0, len(steps), each_n_step): line_data.append(list(zip(xs, data[i, 1:] - energy_min))) facecolors.append(colors[index % 4]) zs.append(data[i, 0]) index += 1 poly = PolyCollection(line_data, facecolors=facecolors, closed=False) poly.set_alpha(0.7) ax.add_collection3d(poly, zs=zs, zdir='x') ax.set_xlabel('Steps') ax.set_ylabel('images') ax.set_zlabel('Energy (J)') ax.set_ylim3d(0, len(xs) + 1) ax.set_xlim3d(0, int(data[-1, 0]) + 1) ax.set_zlim3d(0, np.max(data[:, 1:] - energy_min)) if filename is None: filename = '%s_energy_3d.pdf' % name fig.savefig(filename)
def redraw(self): self._canvas.axes.grid(True, color='gray') # Set axis bounds ymin = ymax = None xmax = 0 xmin = sys.maxint for curve in self._curves.values(): data_x, _, _, range_y, c = curve if len(data_x) == 0: continue xmax = max(xmax, data_x[-1]) xmin = min(xmin, data_x[0]) if ymin is None: ymin = range_y[0] ymax = range_y[1] else: ymin = min(range_y[0], ymin) ymax = max(range_y[1], ymax) # pad the min/max # delta = max(ymax - ymin, 0.1) # ymin -= .05 * delta # ymax += .05 * delta if self._autoscroll and ymin is not None: self._canvas.axes.set_xbound(lower=xmin, upper=xmax) self._canvas.axes.set_zbound(lower=ymin, upper=ymax) self._canvas.axes.set_ybound(lower=0, upper=len(self._curves.keys())) # create poly object verts = [] colors = [] for curve_id in self._curves_verts.keys(): (data_x, data_y) = self._curves_verts[curve_id] colors.append(self._curves[curve_id][4]) if self._use_poly: verts.append([(xmin, ymin)] + list(zip(data_x, data_y)) + [(xmax, ymin)]) else: verts.append(zip(data_x, data_y)) line_num = len(self._curves.keys()) if self._use_poly: poly = PolyCollection(verts, facecolors=colors, closed=False) else: poly = LineCollection(verts, colors=colors) poly.set_alpha(0.7) self._canvas.axes.cla() self._canvas.axes.add_collection3d(poly, zs=range(line_num), zdir='y') self._update_legend() self._canvas.draw()
def plot_triangles(p, adjustLowerLeft=False, values=None, values_cmap=matplotlib.cm.jet, edgecolors='k'): """ Add mesh triangles to a pyplot plot @param p = object holding sww vertex information (from util.get_output) @param adjustLowerLeft = if TRUE, use spatial coordinates, otherwise use ANUGA internal coordinates @param values = list or array of length(p.vols), or None. All triangles are assigned this value (for face plotting colors). @param values_cmap = colormap for faces [e.g. values_cmap = matplotlib.cm.get_cmap('spectral')] @param edgecolors = edge color for polygons (using matplotlib.colors notation). Use 'none' for no color """ import matplotlib from matplotlib import pyplot as pyplot from matplotlib.collections import PolyCollection x0=p.xllcorner y0=p.yllcorner # Make vertices for PolyCollection Object vertices = [] for i in range(len(p.vols)): k1=p.vols[i][0] k2=p.vols[i][1] k3=p.vols[i][2] tri_coords = numpy.array([ [p.x[k1], p.y[k1]], [p.x[k2], p.y[k2]], [p.x[k3], p.y[k3]] ]) if adjustLowerLeft: tri_coords[:,0] = tri_coords[:,0] + x0 tri_coords[:,1] = tri_coords[:,1] + y0 vertices.append(tri_coords) # Make PolyCollection if values is None: all_poly = PolyCollection( vertices, array = numpy.zeros(len(vertices)), edgecolors=edgecolors) all_poly.set_facecolor('none') else: try: lv = len(values) except: values = numpy.array(len(p.vols)*[values]) lv = len(values) msg = 'len(values) must be the same as len(p.vols) (or values can be a constant)' assert lv==len(p.vols), msg all_poly = PolyCollection( vertices, array = values, cmap = values_cmap, edgecolors=edgecolors) # Add to plot # FIXME: To see the triangles, this might require that the user does # something else to the plot? pyplot.gca().add_collection(all_poly)
def _waveform_3d(self, fig_type, zmin, zmax, alpha, cmap): fig = plt.figure(figsize=(10, 10)) ax = fig.gca(projection='3d') num_times = self._inspector.num_times num_samples = self._inspector.num_samples if fig_type == 'surf': x = np.arange(0, num_samples) y = np.arange(0, num_times) x, y = np.meshgrid(x, y) z = self._inspector.waveform surf = ax.plot_surface(x, y, z, rstride=3, cstride=3, cmap=cmap, shade=True, linewidth=0, antialiased=False) # ax.zaxis.set_major_locator(LinearLocator(10)) # ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) fig.colorbar(surf, shrink=0.5, aspect=5) else: waveforms = [] for y_index in range(num_times): waveform = np.ndarray(shape=(num_samples, 2), dtype=np.float64) waveform[:, 0] = np.arange(0, num_samples) waveform[:, 1] = self._inspector.waveform[y_index] waveforms.append(waveform) line_widths = [0.5] * num_times # TODO (forman, 20160725): check why cmap is not recognized if fig_type == 'poly': edge_colors = ((0.2, 0.2, 1., 0.7),) * num_times face_colors = ((1., 1., 1., 0.5),) * num_times collection = PolyCollection(waveforms, cmap=cmap, linewidths=line_widths, edgecolors=edge_colors, facecolors=face_colors) else: colors = ((0.2, 0.2, 1., 0.7),) * num_times collection = LineCollection(waveforms, cmap=cmap, linewidths=line_widths, colors=colors) collection.set_alpha(alpha) ax.add_collection3d(collection, zs=np.arange(0, num_times), zdir='y') wf_min, wf_max = self._inspector.waveform_range ax.set_xlabel('Echo Sample Index') ax.set_xlim3d(0, num_samples - 1) ax.set_ylabel('Time Index') ax.set_ylim3d(0, num_times - 1) ax.set_zlabel('Waveform') ax.set_zlim3d(zmin if zmin is not None else wf_min, zmax if zmax is not None else wf_max) if self._interactive: plt.show() else: self.savefig("fig-waveform-3d-%s.png" % fig_type)
def shape(self, height, yrange, rotated): g = rlg2mpl.Group() (X, Y, I) = (0, 1, 2) shapes = [self.shapes, self.rshapes][rotated] trans = TransformScalePart(g.combined_transform) artists = [] for (motif, cvalues, offsets) in self.per_shape_values: shape = shapes[motif] a = PolyCollection([shape], closed=True, facecolors=cvalues, edgecolors=cvalues, offsets=offsets, transOffset=g.combined_transform) g.add(a) a.set_transform(trans) return g
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(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()
project = AggregationAPI(348, public_panoptes_connection=True) subject_image = project.__image_setup__(subject_id) for minimum_users in [8]: print minimum_users fig, ax = plt.subplots() image_file = cbook.get_sample_data(subject_image) image = plt.imread(image_file) # fig, ax = plt.subplots() im = ax.imshow(image) all_vertices = [] with open("/tmp/348/4_ComplexAMOS/vegetation_polygons_heatmap.csv", "rb") as f: polygon_reader = csv.reader(f) next(polygon_reader, None) for row in polygon_reader: if int(row[1]) == minimum_users: vertices = json.loads(row[2]) all_vertices.append(vertices) all_vertices = np.asarray(all_vertices) coll = PolyCollection(all_vertices, alpha=0.3) ax.add_collection(coll) ax.autoscale_view() plt.show()
def volume_overlay(ax, opens, closes, volumes, colorup='k', colordown='r', width=4, alpha=1.0): """Add a volume overlay to the current axes. The opens and closes are used to determine the color of the bar. -1 is missing. If a value is missing on one it must be missing on all Parameters ---------- ax : `Axes` an Axes instance to plot to opens : sequence a sequence of opens closes : sequence a sequence of closes volumes : sequence a sequence of volumes width : int the bar width in points colorup : color the color of the lines where close >= open colordown : color the color of the lines where close < open alpha : float bar transparency Returns ------- ret : `barCollection` The `barrCollection` added to the axes """ r, g, b = colorConverter.to_rgb(colorup) colorup = r, g, b, alpha r, g, b = colorConverter.to_rgb(colordown) colordown = r, g, b, alpha colord = {True: colorup, False: colordown, } colors = [colord[open < close] for open, close in zip(opens, closes) if open != -1 and close != -1] delta = width / 2. bars = [((i - delta, 0), (i - delta, v), (i + delta, v), (i + delta, 0)) for i, v in enumerate(volumes) if v != -1] barCollection = PolyCollection(bars, facecolors=colors, edgecolors=((0, 0, 0, 1), ), antialiaseds=(0,), linewidths=(0.5,), ) ax.add_collection(barCollection) corners = (0, 0), (len(bars), max(volumes)) ax.update_datalim(corners) ax.autoscale_view() # add these last return barCollection
continue values = line.split() if not values: continue if values[0] == 'v': V.append([float(x) for x in values[1:4]]) elif values[0] == 'f': F.append([int(x) for x in values[1:4]]) V, F = np.array(V), np.array(F) - 1 V = (V - (V.max(0) + V.min(0)) / 2) / max(V.max(0) - V.min(0)) V = np.c_[V, np.ones(len(V))] @ perspective(25, 1, 1, 100).T V /= V[:, 3].reshape(-1, 1) T = V[F][..., :2] # Rendering fig = plt.figure(figsize=(6, 6)) ax = fig.add_axes([0, 0, 1, 1], xlim=[-1, +1], ylim=[-1, +1], aspect=1, frameon=False) collection = PolyCollection(T, closed=True, linewidth=0.1, facecolor="None", edgecolor="black") ax.add_collection(collection) plt.savefig("bunny-2.png", dpi=300) plt.show()
def plot_probe(probe, ax=None, contacts_colors=None, with_channel_index=False, with_contact_id=False, with_device_index=False, text_on_contact=None, first_index='auto', contacts_values=None, cmap='viridis', title=True, contacts_kargs={}, probe_shape_kwargs={}, xlims=None, ylims=None, zlims=None, show_channel_on_click=False): """Plot a Probe object. Generates a 2D or 3D axis, depending on Probe.ndim Parameters ---------- probe : Probe The probe object ax : matplotlib.axis, optional The axis to plot the probe on. If None, an axis is created, by default None contacts_colors : matplotlib color, optional The color of the contacts, by default None with_channel_index : bool, optional If True, channel indices are displayed on top of the channels, by default False with_contact_id : bool, optional If True, channel ids are displayed on top of the channels, by default False with_device_index : bool, optional If True, device channel indices are displayed on top of the channels, by default False text_on_contact: None or list or numpy.array Addintional text to plot on each contact first_index : str, optional The first index of the contacts, by default 'auto' (taken from channel ids) contacts_values : np.array, optional Values to color the contacts with, by default None cmap : str, optional [description], by default 'viridis' title : bool, optional If True, the axis title is set to the probe name, by default True contacts_kargs : dict, optional Dict with kwargs for contacts (e.g. alpha, edgecolor, lw), by default {} probe_shape_kwargs : dict, optional Dict with kwargs for probe shape (e.g. alpha, edgecolor, lw), by default {} xlims : tuple, optional Limits for x dimension, by default None ylims : tuple, optional Limits for y dimension, by default None zlims : tuple, optional Limits for z dimension, by default None show_channel_on_click : bool, optional If True, the channel information is shown upon click, by default False Returns ------- poly : PolyCollection The polygon collection for contacts poly_contour : PolyCollection The polygon collection for the probe shape """ import matplotlib.pyplot as plt if probe.ndim == 2: from matplotlib.collections import PolyCollection elif probe.ndim == 3: from mpl_toolkits.mplot3d.art3d import Poly3DCollection if ax is None: if probe.ndim == 2: fig, ax = plt.subplots() ax.set_aspect('equal') else: fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection='3d') else: fig = ax.get_figure() if first_index == 'auto': if 'first_index' in probe.annotations: first_index = probe.annotations['first_index'] elif probe.annotations.get('manufacturer', None) == 'neuronexus': # neuronexus is one based indexing first_index = 1 else: first_index = 0 assert first_index in (0, 1) _probe_shape_kwargs = dict( facecolor='green', edgecolor='k', lw=0.5, alpha=0.3) _probe_shape_kwargs.update(probe_shape_kwargs) _contacts_kargs = dict(alpha=0.7, edgecolor=[0.3, 0.3, 0.3], lw=0.5) _contacts_kargs.update(contacts_kargs) n = probe.get_contact_count() if contacts_colors is None and contacts_values is None: contacts_colors = ['orange'] * n elif contacts_colors is not None: contacts_colors = contacts_colors elif contacts_values is not None: contacts_colors = None vertices = probe.get_contact_vertices() if probe.ndim == 2: poly = PolyCollection( vertices, color=contacts_colors, **_contacts_kargs) ax.add_collection(poly) elif probe.ndim == 3: poly = Poly3DCollection( vertices, color=contacts_colors, **_contacts_kargs) ax.add_collection3d(poly) if contacts_values is not None: poly.set_array(contacts_values) poly.set_cmap(cmap) if show_channel_on_click: assert probe.ndim == 2, 'show_channel_on_click works only for ndim=2' def on_press(event): return _on_press(probe, event) fig.canvas.mpl_connect('button_press_event', on_press) fig.canvas.mpl_connect('button_release_event', on_release) # probe shape planar_contour = probe.probe_planar_contour if planar_contour is not None: if probe.ndim == 2: poly_contour = PolyCollection( [planar_contour], **_probe_shape_kwargs) ax.add_collection(poly_contour) elif probe.ndim == 3: poly_contour = Poly3DCollection( [planar_contour], **_probe_shape_kwargs) ax.add_collection3d(poly_contour) else: poly_contour = None if text_on_contact is not None: text_on_contact = np.asarray(text_on_contact) assert text_on_contact.size == probe.get_contact_count() if with_channel_index or with_contact_id or with_device_index or text_on_contact is not None: if probe.ndim == 3: raise NotImplementedError('Channel index is 2d only') for i in range(n): txt = [] if with_channel_index: txt.append(f'{i + first_index}') if with_contact_id and probe.contact_ids is not None: contact_id = probe.contact_ids[i] txt.append(f'id{contact_id}') if with_device_index and probe.device_channel_indices is not None: chan_ind = probe.device_channel_indices[i] txt.append(f'dev{chan_ind}') if text_on_contact is not None: txt.append(f'{text_on_contact[i]}') txt = '\n'.join(txt) x, y = probe.contact_positions[i] ax.text(x, y, txt, ha='center', va='center', clip_on=True) if xlims is None or ylims is None or (zlims is None and probe.ndim == 3): xlims, ylims, zlims = get_auto_lims(probe) ax.set_xlim(*xlims) ax.set_ylim(*ylims) if probe.si_units == "um": unit_str = "($\mu m$)" else: unit_str = f"({probe.si_units})" ax.set_xlabel(f'x {unit_str}', fontsize=15) ax.set_ylabel(f'y {unit_str}', fontsize=15) if probe.ndim == 3: ax.set_zlim(zlims) ax.set_zlabel('z') if probe.ndim == 2: ax.set_aspect('equal') if title: ax.set_title(probe.get_title()) return poly, poly_contour
def show_mesh_2d(axes, mesh, nodecolor='k', edgecolor='k', cellcolor='grey', aspect='equal', linewidths=1, markersize=20, showaxis=False, showcolorbar=False, cmap='gnuplot2', box=None): try: axes.set_aspect(aspect) except NotImplementedError: pass 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() f.colorbar(mapper, shrink=0.5, ax=axes) node = mesh.entity('node') cell = mesh.entity('cell') if mesh.meshtype not in {'polygon', 'hepolygon', 'halfedge', 'halfedge2d'}: if mesh.geo_dimension() == 2: poly = PolyCollection(node[cell[:, mesh.ds.ccw], :]) else: poly = a3.art3d.Poly3DCollection(node[cell, :]) else: cell, cellLocation = cell 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 box is None: 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)
B_wass[:, i] = ot.bregman.barycenter(A, M, reg, weights) #%% plot interpolation pl.figure(3) cmap = pl.cm.get_cmap('viridis') verts = [] zs = alpha_list for i, z in enumerate(zs): ys = B_l2[:, i] verts.append(list(zip(x, ys))) ax = pl.gcf().gca(projection='3d') poly = PolyCollection(verts, facecolors=[cmap(a) for a in alpha_list]) poly.set_alpha(0.7) ax.add_collection3d(poly, zs=zs, zdir='y') ax.set_xlabel('x') ax.set_xlim3d(0, n) ax.set_ylabel('$\\alpha$') ax.set_ylim3d(0, 1) ax.set_zlabel('') ax.set_zlim3d(0, B_l2.max() * 1.01) pl.title('Barycenter interpolation with l2') pl.tight_layout() pl.figure(4) cmap = pl.cm.get_cmap('viridis') verts = [] zs = alpha_list
def overlayFan(myData, myMap, myFig, param, coords='geo', gsct=0, site=None, fov=None, gs_flg=[], fill=True, velscl=1000., dist=1000., cmap=None, norm=None, alpha=1): """A function of overlay radar scan data on a map Parameters ---------- myData : pydarn.sdio.radDataTypes.scanData or pydarn.sdio.radDataTypes.beamData or list of pydarn.sdio.radDataTypes.beamData objects A radar beam object, a radar scanData object, or simply a list of radar beams myMap : The map we are plotting on myFig : Figure object that we are plotting to coords : Optional[str] The coordinates we are plotting in. Default: geo param : Optional[str] The parameter to be plotted, valid inputs are 'velocity', 'power', 'width', 'elevation', 'phi0'. default = 'velocity gsct : Optional[boolean] A flag indicating whether we are distinguishing ground scatter. default = 0 intensities : Optional[ ] A list of intensities (used for colorbar) fov : Optional[pydarn.radar.radFov.fov] A radar fov object gs_flg : Optional[ ] A list of gs flags, 1 per range gate fill : Optional[boolean] A flag indicating whether to plot filled or point RB cells. default = True velscl : Optional[float] The velocity to use as baseline for velocity vector length, only applicable if fill = 0. default = 1000 lines : Optional[ ] An array to have the endpoints of velocity vectors. only applicable if fill = 0. default = [] dist : Optional [float] The length in map projection coords of a velscl length velocity vector. default = 1000. km Returns ------- intensities pcoll lcoll Example ------- overlayFan(aBeam,myMap,param,coords,gsct=gsct,site=sites[i],fov=fovs[i], verts=verts,intensities=intensities,gs_flg=gs_flg) """ from davitpy import pydarn if (site is None): site = pydarn.radar.site(radId=myData[0].stid, dt=myData[0].time) if (fov is None): fov = pydarn.radar.radFov.fov(site=site, rsep=myData[0].prm.rsep, ngates=myData[0].prm.nrang + 1, nbeams=site.maxbeam, coords=coords, date_time=myData[0].time) if (isinstance(myData, pydarn.sdio.beamData)): myData = [myData] gs_flg, lines = [], [] if fill: verts, intensities = [], [] else: verts, intensities = [[], []], [[], []] # loop through gates with scatter for myBeam in myData: for k in range(0, len(myBeam.fit.slist)): if myBeam.fit.slist[k] not in fov.gates: continue r = myBeam.fit.slist[k] if fill: x1, y1 = myMap(fov.lonFull[myBeam.bmnum, r], fov.latFull[myBeam.bmnum, r]) x2, y2 = myMap(fov.lonFull[myBeam.bmnum, r + 1], fov.latFull[myBeam.bmnum, r + 1]) x3, y3 = myMap(fov.lonFull[myBeam.bmnum + 1, r + 1], fov.latFull[myBeam.bmnum + 1, r + 1]) x4, y4 = myMap(fov.lonFull[myBeam.bmnum + 1, r], fov.latFull[myBeam.bmnum + 1, r]) # save the polygon vertices verts.append( ((x1, y1), (x2, y2), (x3, y3), (x4, y4), (x1, y1))) # save the param to use as a color scale if (param == 'velocity'): intensities.append(myBeam.fit.v[k]) elif (param == 'power'): intensities.append(myBeam.fit.p_l[k]) elif (param == 'width'): intensities.append(myBeam.fit.w_l[k]) elif (param == 'elevation' and myBeam.prm.xcf): intensities.append(myBeam.fit.elv[k]) elif (param == 'phi0' and myBeam.prm.xcf): intensities.append(myBeam.fit.phi0[k]) else: x1, y1 = myMap(fov.lonCenter[myBeam.bmnum, r], fov.latCenter[myBeam.bmnum, r]) verts[0].append(x1) verts[1].append(y1) x2, y2 = myMap(fov.lonCenter[myBeam.bmnum, r + 1], fov.latCenter[myBeam.bmnum, r + 1]) theta = math.atan2(y2 - y1, x2 - x1) x2, y2 = x1 + myBeam.fit.v[k] / velscl * (-1.0) * \ math.cos(theta) * dist, y1 + myBeam.fit.v[k] / velscl * \ (-1.0) * math.sin(theta) * dist lines.append(((x1, y1), (x2, y2))) # save the param to use as a color scale if (param == 'velocity'): intensities[0].append(myBeam.fit.v[k]) elif (param == 'power'): intensities[0].append(myBeam.fit.p_l[k]) elif (param == 'width'): intensities[0].append(myBeam.fit.w_l[k]) elif (param == 'elevation' and myBeam.prm.xcf): intensities[0].append(myBeam.fit.elv[k]) elif (param == 'phi0' and myBeam.prm.xcf): intensities[0].append(myBeam.fit.phi0[k]) if (myBeam.fit.p_l[k] > 0): intensities[1].append(myBeam.fit.p_l[k]) else: intensities[1].append(0.) if (gsct): gs_flg.append(myBeam.fit.gflg[k]) # do the actual overlay if (fill): # if we have data if (verts != []): if (gsct == 0): inx = numpy.arange(len(verts)) else: inx = numpy.where(numpy.array(gs_flg) == 0) x = PolyCollection( numpy.array(verts)[numpy.where(numpy.array(gs_flg) == 1)], facecolors='.3', linewidths=0, zorder=5, alpha=alpha) myFig.gca().add_collection(x, autolim=True) pcoll = PolyCollection(numpy.array(verts)[inx], edgecolors='face', linewidths=0, closed=False, zorder=4, alpha=alpha, cmap=cmap, norm=norm) # set color array to intensities pcoll.set_array(numpy.array(intensities)[inx]) myFig.gca().add_collection(pcoll, autolim=True) return intensities, pcoll else: # if we have data if (verts != [[], []]): if (gsct == 0): inx = numpy.arange(len(verts[0])) else: inx = numpy.where(numpy.array(gs_flg) == 0) # plot the ground scatter as open circles x = myFig.scatter( numpy.array( verts[0])[numpy.where(numpy.array(gs_flg) == 1)], numpy.array( verts[1])[numpy.where(numpy.array(gs_flg) == 1)], s=.1 * numpy.array( intensities[1])[numpy.where(numpy.array(gs_flg) == 1)], zorder=5, marker='o', linewidths=.5, facecolors='w', edgecolors='k') myFig.gca().add_collection(x, autolim=True) # plot the i-s as filled circles ccoll = myFig.gca().scatter(numpy.array(verts[0])[inx], numpy.array(verts[1])[inx], s=.1 * numpy.array(intensities[1])[inx], zorder=10, marker='o', linewidths=.5, edgecolors='face', cmap=cmap, norm=norm) # set color array to intensities ccoll.set_array(numpy.array(intensities[0])[inx]) myFig.gca().add_collection(ccoll) # plot the velocity vectors lcoll = LineCollection(numpy.array(lines)[inx], linewidths=.5, zorder=12, cmap=cmap, norm=norm) lcoll.set_array(numpy.array(intensities[0])[inx]) myFig.gca().add_collection(lcoll) return intensities, lcoll
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 _gen2d3d(*args, **pltkwargs): # UPDATE """ Abstract layout for 2d plot. For convienence, a few special labels, colorbar and background keywords have been implemented. If these are not adequate, it one can add custom colorbars, linelabels background images etc... easily just by using respecitve calls to plot (plt.colorbar(), plt.imshow(), plt.clabel() ); my implementations are only for convienences and some predefined, cool styles. countours: Number of desired contours from output. label: Predefined label types. For now, only integer values 1,2. Use plt.clabel to add a custom label. background: Integers 1,2 will add gray or autumn colormap under contour plot. Use plt.imgshow() to generate custom background, or pass a PIL-opened image (note, proper image scaling not yet implemented). c_iso, r_iso: These control how man column and row iso lines will be projected onto the 3d plot. For example, if c_iso=10, then 10 isolines will be plotted as columns, despite the actual length of the columns. Alternatively, one can pass in c_stride directly, which is a column step size rather than an absolute number, and c_iso will be disregarded. fill: bool (False) Fill between contour lines. **pltkwargs: Will be passed directly to plt.contour(). Returns ------- tuple: (Axes, SurfaceFunction) Returns axes object and the surface function (e.g. contours for contour plot. Surface for surface plot. """ # Use a label mapper to allow for datetimes in any plot x/y axis _x_dti = _ = _y_dti = False # Passed Spectra if len(args) == 1: ts = args[0] try: index = np.array([dates.date2num(x) for x in ts.index]) _x_dti = True except AttributeError: index = ts.index.values #VALUES NECESSARY FOR POLY CMAP try: cols = np.array([dates.date2num(x) for x in ts.columns]) _y_dti = True except AttributeError: cols = ts.columns.values #VALUES NECESSARY FOR POLY CMAP yy, xx = np.meshgrid(cols, index) # Passed xx, yy, ts/zz elif len(args) == 3: xx, yy, ts = args cols, index = ts.columns.values, ts.index.values else: raise PlotError( "Please pass a single spectra, or xx, yy, zz. Got %s args" % len(args)) # Boilerplate from basic_plots._genplot(); could refactor as decorator xlabel = pltkwargs.pop('xlabel', '') ylabel = pltkwargs.pop('ylabel', '') zlabel = pltkwargs.pop('zlabel', '') title = pltkwargs.pop('title', '') # Choose plot kind kind = pltkwargs.pop('kind', 'contour') grid = pltkwargs.pop('grid', '') # pltkwargs.setdefault('legend', False) #(any purpose in 2d?) # LEGEND FOR 2D PLOT: http://stackoverflow.com/questions/10490302/how-do-you-create-a-legend-for-a-contour-plot-in-matplotlib pltkwargs.setdefault('linewidth', 1) cbar = pltkwargs.pop('cbar', False) fig = pltkwargs.pop('fig', None) ax = pltkwargs.pop('ax', None) fill = pltkwargs.pop('fill', False) xlim = pltkwargs.pop('xlim', None) ylim = pltkwargs.pop('ylim', None) zlim = pltkwargs.pop('zlim', None) #Private attributes _modifyax = pltkwargs.pop('_modifyax', True) contours = pltkwargs.pop('contours', 6) label = pltkwargs.pop('label', None) projection = None if kind in PLOTPARSER.plots_3d: projection = '3d' elev = pltkwargs.pop('elev', 35) azim = pltkwargs.pop('azim', -135) view = pltkwargs.pop('view', None) if view: if view == 1: elev, azim = 35, -135 elif view == 2: elev, azim = 35, -45 elif view == 3: elev, azim = 20, -10 # Side view elif view == 4: elev, azim = 20, -170 elif view == 5: elev, azim = 0, -90 elif view == 6: elev, azim = 65, -90 else: raise PlotError('View must be between 1 and 6; otherwise set' ' "elev" and "azim" keywords.') # Orientation of zlabel (doesn't work...) _zlabel_rotation = 0.0 if azim < 0: _zlabel_rotation = 90.0 c_iso = pltkwargs.pop('c_iso', 10) r_iso = pltkwargs.pop('r_iso', 10) if c_iso > ts.shape[1] or c_iso < 0: raise PlotError('"c_iso" must be between 0 and %s, got "%s"' % (ts.shape[1], c_iso)) if r_iso > ts.shape[0] or r_iso < 0: raise PlotError('"r_iso" must be between 0 and %s, got "%s"' % (ts.shape[0], r_iso)) if c_iso == 0: cstride = 0 else: cstride = _ir(ts.shape[1] / float(c_iso)) if r_iso == 0: rstride = 0 else: rstride = _ir(ts.shape[0] / float(r_iso)) pltkwargs.setdefault('cstride', cstride) pltkwargs.setdefault('rstride', rstride) elif kind == 'contour': pass else: raise PlotError('_gen2d3d invalid kind: "%s". ' 'Choose from %s' % (kind, PLOTPARSER.plots_2d_3d)) # Is this the best logic for 2d/3d fig? if not ax: f = plt.figure() # ax = f.gca(projection=projection) ax = f.add_subplot(111, projection=projection) if not fig: fig = f labelsize = pltkwargs.pop('labelsize', 'medium') #Can also be ints titlesize = pltkwargs.pop('titlesize', 'large') ticksize = pltkwargs.pop('ticksize', '') #Put in default and remove bool gate # PLT.CONTOUR() doesn't take 'color'; rather, takes 'colors' for now if 'color' in pltkwargs: if kind == 'contour': pltkwargs['colors'] = pltkwargs.pop('color') # Convienence method to pass in string colors if 'colormap' in pltkwargs: pltkwargs['cmap'] = pltkwargs.pop('colormap') if 'cmap' in pltkwargs: if isinstance(pltkwargs['cmap'], basestring): pltkwargs['cmap'] = pu.cmget(pltkwargs['cmap']) # Contour Plots # ------------- # Broken background image ### More here http://matplotlib.org/examples/pylab_examples/image_demo3.html ### # Refactored with xx, yy instead of df.columns/index UNTESTED #if background: #xmin, xmax, ymin, ymax = xx.min(), xx.max(), yy.min(), yy.max() ## Could try rescaling contour rather than image: ##http://stackoverflow.com/questions/10850882/pyqt-matplotlib-plot-contour-data-on-top-of-picture-scaling-issue #if background==1: #im = ax.imshow(ts, interpolation='bilinear', origin='lower', #cmap=cm.gray, extent=(xmin, xmax, ymin, ymax)) #### This will take a custom image opened in PIL or it will take plt.imshow() returned from somewhere else #else: #try: #im = ax.imshow(background) #### Perhaps image was not correctly opened #except Exception: #raise badvalue_error(background, 'integer 1,2 or a PIL-opened image') # Note this overwrites the 'contours' variable from an int to array if kind == 'contour' or kind == 'contour3d': if fill: mappable = ax.contourf(xx, yy, ts, contours, **pltkwargs) #linewidths is a pltkwargs arg else: mappable = ax.contour(xx, yy, ts, contours, **pltkwargs) ### Pick a few label styles to choose from. if label: if label == 1: ax.clabel(inline=1, fontsize=10) elif label == 2: ax.clabel(levels[1::2], inline=1, fontsize=10) #label every second line else: raise PlotError(label, 'integer of value 1 or 2') elif kind == 'surf': mappable = ax.plot_surface(xx, yy, ts, **pltkwargs) # pltkwargs.pop('edgecolors') wires = overload_plot_wireframe(ax, xx, yy, ts, **pltkwargs) # print np.shape(wires._segments3d) wires = wire_cmap(wires, ax, cmap='jet') elif kind == 'wire': pltkwargs.setdefault('color', 'black') mappable = overload_plot_wireframe(ax, xx, yy, ts, **pltkwargs) elif kind == 'waterfall': edgecolors = pltkwargs.setdefault('edgecolors', None) pltkwargs.setdefault('closed', False) alpha = pltkwargs.setdefault('alpha', None) # Need to handle cmap/colors a bit differently for PolyCollection API if 'color' in pltkwargs: pltkwargs['facecolors'] = pltkwargs.pop('color') cmap = pltkwargs.setdefault('cmap', None) if alpha is None: #as opposed to 0 alpha = 0.6 * (13.0 / ts.shape[1]) if alpha > 0.6: alpha = 0.6 #Delete stride keywords for key in ['cstride', 'rstride']: try: del pltkwargs[key] except KeyError: pass # Verts are index dotted with data verts = [] for col in ts.columns: values = ts[col] values[0], values[-1] = values.min().min(), values.min().min() verts.append(list(zip(ts.index, values))) mappable = PolyCollection(verts, **pltkwargs) if cmap: mappable.set_array( cols) #If set array in __init__, autogens a cmap! mappable.set_cmap(pltkwargs['cmap']) mappable.set_alpha(alpha) #zdir is the direction used to plot; dont' fully understand ax.add_collection3d(mappable, zs=cols, zdir='x') # custom limits/labels polygon plot (reverse x,y) if not ylim: ylim = (max(index), min(index)) #REVERSE AXIS FOR VIEWING PURPOSES if not xlim: xlim = (min(cols), max(cols)) #x if not zlim: zlim = (min(ts.min()), max(ts.max()) ) #How to get absolute min/max of ts values # Reverse labels/DTI call for correct orientaion HACK HACK HACK xlabel, ylabel = ylabel, xlabel _x_dti, _y_dti = _y_dti, _x_dti azim = -1 * azim # General Features # ---------------- # Some applications (like add_projection) shouldn't alther axes features if not _modifyax: return (ax, mappable) if cbar: # Do I want colorbar outside of fig? Wouldn't be better on axes? try: fig.colorbar(mappable, ax=ax) except Exception: raise PlotError("Colorbar failed; did you pass a colormap?") if grid: ax.grid() # Format datetime axis # ------------------- if _x_dti: ax.xaxis.set_major_formatter(mplticker.FuncFormatter(format_date)) # Uncomment for custom 3d timestamp orientation # if projection: # for t1 in ax.yaxis.get_ticklabels(): # t1.set_ha('right') # t1.set_rotation(30) # ax.yaxis._axinfo['label']['space_factor'] = _TIMESTAMPPADDING if _y_dti: ax.yaxis.set_major_formatter(mplticker.FuncFormatter(format_date)) # Uncomment for custom 3d timestamp orientation # if projection: # for t1 in ax.yaxis.get_ticklabels(): # t1.set_ha('right') # t1.set_rotation(30) # ax.yaxis._axinfo['label']['space_factor'] = _TIMESTAMPPADDING if xlim: ax.set_xlim3d(xlim) if ylim: ax.set_ylim3d(ylim) if zlim: ax.set_zlim3d(zlim) # Set elevation/azimuth for 3d plots if projection: ax.view_init(elev, azim) ax.set_zlabel(zlabel, fontsize=labelsize, rotation=_zlabel_rotation) ax.set_xlabel(xlabel, fontsize=labelsize) ax.set_ylabel(ylabel, fontsize=labelsize) ax.set_title(title, fontsize=titlesize) # Return Ax, contours/surface/polygons etc... return (ax, mappable)
def triplot(mesh, axes=None, interior_kw={}, boundary_kw={}): r"""Plot a mesh with a different color for each boundary segment The interior and boundary keyword arguments can be any keyword argument for :class:`LineCollection <matplotlib.collections.LinecCollection>` and related types. :arg mesh: mesh to be plotted :arg axes: matplotlib :class:`Axes <matplotlib.axes.Axes>` object on which to plot mesh :arg interior_kw: keyword arguments to apply when plotting the mesh interior :arg boundary_kw: keyword arguments to apply when plotting the mesh boundary :return: list of matplotlib :class:`Collection <matplotlib.collections.Collection>` objects """ gdim = mesh.geometric_dimension() tdim = mesh.topological_dimension() BoundaryCollection, InteriorCollection = _get_collection_types(gdim, tdim) quad = mesh.ufl_cell().cellname() == "quadrilateral" if axes is None: figure = plt.figure() if gdim == 3: axes = figure.add_subplot(111, projection='3d') else: axes = figure.add_subplot(111) coordinates = mesh.coordinates element = coordinates.function_space().ufl_element() if element.degree() != 1: # Interpolate to piecewise linear. V = VectorFunctionSpace(mesh, element.family(), 1) coordinates = interpolate(coordinates, V) coords = coordinates.dat.data_ro result = [] interior_kw = dict(interior_kw) # If the domain isn't a 3D volume, draw the interior. if tdim <= 2: cell_node_map = coordinates.cell_node_map().values idx = (tuple(range(tdim + 1)) if not quad else (0, 1, 3, 2)) + (0, ) vertices = coords[cell_node_map[:, idx]] interior_kw["edgecolors"] = interior_kw.get("edgecolors", "k") interior_kw["linewidths"] = interior_kw.get("linewidths", 1.0) if gdim == 2: interior_kw["facecolors"] = interior_kw.get("facecolors", "none") interior_collection = InteriorCollection(vertices, **interior_kw) axes.add_collection(interior_collection) result.append(interior_collection) # Add colored lines/polygons for the boundary facets facets = mesh.exterior_facets local_facet_ids = facets.local_facet_dat.data_ro exterior_facet_node_map = coordinates.exterior_facet_node_map().values topology = coordinates.function_space().finat_element.cell.get_topology() mask = np.zeros(exterior_facet_node_map.shape, dtype=bool) for facet_index, local_facet_index in enumerate(local_facet_ids): mask[facet_index, topology[tdim - 1][local_facet_index]] = True faces = exterior_facet_node_map[mask].reshape(-1, tdim) markers = facets.unique_markers color_key = "colors" if tdim <= 2 else "facecolors" boundary_colors = boundary_kw.pop(color_key, None) if boundary_colors is None: cmap = matplotlib.cm.get_cmap("Dark2") num_markers = len(markers) colors = cmap([k / num_markers for k in range(num_markers)]) else: colors = matplotlib.colors.to_rgba_array(boundary_colors) boundary_kw = dict(boundary_kw) if tdim == 3: boundary_kw["edgecolors"] = boundary_kw.get("edgecolors", "k") boundary_kw["linewidths"] = boundary_kw.get("linewidths", 1.0) for marker, color in zip(markers, colors): face_indices = facets.subset(int(marker)).indices marker_faces = faces[face_indices, :] vertices = coords[marker_faces] _boundary_kw = dict(**{ color_key: color, "label": marker }, **boundary_kw) marker_collection = BoundaryCollection(vertices, **_boundary_kw) axes.add_collection(marker_collection) result.append(marker_collection) # Dirty hack to enable legends for 3D volume plots. See the function # `Poly3DCollection.set_3d_properties`. for collection in result: if isinstance(collection, Poly3DCollection): collection._facecolors2d = PolyCollection.get_facecolor(collection) collection._edgecolors2d = PolyCollection.get_edgecolor(collection) _autoscale_view(axes, coords) return result
ax = fig.gca(projection='3d') fig.set_tight_layout(True) fig.tight_layout(pad=10.4, w_pad=10.5, h_pad=11.0) def cc(arg): return mcolors.to_rgba(arg, alpha=0.6) xs = wl verts = [] zs = [0.0, 1.0, 2.0, 3.0, 4.0] for z in zs: ys = dict_for_dyn[dyn_conc][int(z)][1:1500] ys[0], ys[-1] = 0, 0 verts.append(list(zip(xs, ys))) poly = PolyCollection(verts, facecolors=[cc('r'), cc('g'), cc('b'), cc('y'), cc('r')]) poly.set_alpha(0.4) ax.add_collection3d(poly, zs=zs, zdir='y') ax.set_xlabel('Wavelength, nm',labelpad=20) ax.set_xlim3d(200, 900) ax.set_ylabel('T',labelpad=20) ax.set_ylim3d(0, 4) ax.set_zlabel('I, Relative units',labelpad=20) ax.set_zlim3d(0, max(ys)) if do_save == 1: fig.savefig(sna+'_Dynamic'+dyn_conc+'.jpg',transparent=False,dpi=300,bbox_inches="tight") plt.show()
def index_bar(ax, vals, facecolor='b', edgecolor='l', width=4, alpha=1.0, ): """Add a bar collection graph with height vals (-1 is missing). Parameters ---------- ax : `Axes` an Axes instance to plot to vals : sequence a sequence of values facecolor : color the color of the bar face edgecolor : color the color of the bar edges width : int the bar width in points alpha : float bar transparency Returns ------- ret : `barCollection` The `barrCollection` added to the axes """ facecolors = (colorConverter.to_rgba(facecolor, alpha),) edgecolors = (colorConverter.to_rgba(edgecolor, alpha),) right = width / 2.0 left = -width / 2.0 bars = [((left, 0), (left, v), (right, v), (right, 0)) for v in vals if v != -1] sx = ax.figure.dpi * (1.0 / 72.0) # scale for points sy = ax.bbox.height / ax.viewLim.height barTransform = Affine2D().scale(sx, sy) offsetsBars = [(i, 0) for i, v in enumerate(vals) if v != -1] barCollection = PolyCollection(bars, facecolors=facecolors, edgecolors=edgecolors, antialiaseds=(0,), linewidths=(0.5,), offsets=offsetsBars, transOffset=ax.transData, ) barCollection.set_transform(barTransform) minpy, maxx = (0, len(offsetsBars)) miny = 0 maxy = max([v for v in vals if v != -1]) corners = (minpy, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() # add these last ax.add_collection(barCollection) return barCollection
def volume_overlay3(ax, quotes, colorup='k', colordown='r', width=4, alpha=1.0): """Add a volume overlay to the current axes. quotes is a list of (d, open, high, low, close, volume) and close-open is used to determine the color of the bar Parameters ---------- ax : `Axes` an Axes instance to plot to quotes : sequence of (time, open, high, low, close, ...) sequences data to plot. time must be in float date format - see date2num width : int the bar width in points colorup : color the color of the lines where close1 >= close0 colordown : color the color of the lines where close1 < close0 alpha : float bar transparency Returns ------- ret : `barCollection` The `barrCollection` added to the axes """ r, g, b = colorConverter.to_rgb(colorup) colorup = r, g, b, alpha r, g, b = colorConverter.to_rgb(colordown) colordown = r, g, b, alpha colord = {True: colorup, False: colordown, } dates, opens, highs, lows, closes, volumes = list(zip(*quotes)) colors = [colord[close1 >= close0] for close0, close1 in zip(closes[:-1], closes[1:]) if close0 != -1 and close1 != -1] colors.insert(0, colord[closes[0] >= opens[0]]) right = width / 2.0 left = -width / 2.0 bars = [((left, 0), (left, volume), (right, volume), (right, 0)) for d, open, high, low, close, volume in quotes] sx = ax.figure.dpi * (1.0 / 72.0) # scale for points sy = ax.bbox.height / ax.viewLim.height barTransform = Affine2D().scale(sx, sy) dates = [d for d, open, high, low, close, volume in quotes] offsetsBars = [(d, 0) for d in dates] useAA = 0, # use tuple here lw = 0.5, # and here barCollection = PolyCollection(bars, facecolors=colors, edgecolors=((0, 0, 0, 1),), antialiaseds=useAA, linewidths=lw, offsets=offsetsBars, transOffset=ax.transData, ) barCollection.set_transform(barTransform) minpy, maxx = (min(dates), max(dates)) miny = 0 maxy = max([volume for d, open, high, low, close, volume in quotes]) corners = (minpy, miny), (maxx, maxy) ax.update_datalim(corners) #print 'datalim', ax.dataLim.bounds #print 'viewlim', ax.viewLim.bounds ax.add_collection(barCollection) ax.autoscale_view() return barCollection
def set_verts(self, verts, closed=True): '''Set 3D vertices.''' self.get_vector(verts) # 2D verts will be updated at draw time PolyCollection.set_verts(self, [], closed)
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 __init__(self, map, mask, nest=False, **kwargs): nside = healpix.npix2nside(len(mask)) self.v = pix2quad(nside, mask.nonzero()[0], nest) PolyCollection.__init__(self, self.v, array=map[mask], **kwargs)
def colrboxy(cboxy, colrmap, marks, ncstr=0, nclrm=256): """ Generate a colour bar polycollection with given key box cboxy=[x, y, dx, dy] and colormap, plus marks. The colour index arrays will generated out of given colormap. JGLi01Mar2019 """ ## Input variables include x, y as Numpy Arrays or lists for the ## colorbar locations, the colormap to be plotted, integer list ## or Numpy Array marks for key scale ticks as enlarged polygon. ## Tick labels should be added outside this program when the ## colorbar PolyCollection is drawn in a corresponding plot. ## Workout color bar orientaion by x and y sizes ## and generate poly verts and colors. x0 = cboxy[0] y0 = cboxy[1] bx = cboxy[2] by = cboxy[3] verts = [] pcolr = [] ic = ncstr if (bx > by): ## Horizontal color bar dx = bx / nclrm xkeys = np.arange(nclrm) * dx + x0 ykeys = np.array([y0, y0 + by]) syc = [y0, y0, y0 + by, y0 + by] for xi in xkeys: sxc = [xi, xi + dx, xi + dx, xi] verts.append(list(zip(sxc, syc))) pcolr.append(colrmap(ic)) ic += 1 dm = 1.1 * by sym = [y0, y0, y0 + dm, y0 + dm] for i in marks: xi = xkeys[i] sxc = [xi, xi + dx, xi + dx, xi] verts.append(list(zip(sxc, sym))) pcolr.append(colrmap(i)) else: ## Vertical color bar dy = by / nclrm xkeys = np.array([x0, x0 + bx]) ykeys = np.arange(nclrm) * dy + y0 sxc = [x0, x0 + bx, x0 + bx, x0] for yj in ykeys: syc = [yj, yj, yj + dy, yj + dy] verts.append(list(zip(sxc, syc))) pcolr.append(colrmap(ic)) ic += 1 dm = 1.1 * bx sxm = [x0, x0 + dm, x0 + dm, x0] for j in marks: yj = ykeys[j] syc = [yj, yj, yj + dy, yj + dy] verts.append(list(zip(sxm, syc))) pcolr.append(colrmap(j)) ## Generate PolyCollection cbarpoly = PolyCollection(verts) cbarpoly.set_color(pcolr) return (xkeys, ykeys, cbarpoly)
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(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 swhlocal(swhs, verts, ncels, colrs, config, mdlname='SMC', datx='2018', psfile='output.ps', paprorn='portrait', paprtyp='a3'): """ ## Draw local swh plot with given polycollections and cell ## array. Output as A3 ps file. JGLi28Feb2019 """ # 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()
# print 'in update' depth = slider1.val mDot[0].set_data([.5, -.2]) mDot[0].set_3d_properties(depth, zdir='y') # plt.show() plt.pause(.001) slider1.on_changed(update1) # 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') ax.add_collection3d(poly1, zs=vertsZ, zdir='y') # Front 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] poly2 = PolyCollection(vertsXY) poly2.set_alpha(0.7) poly2.set_color('w') poly2.set_edgecolor('k') ax.add_collection3d(poly2, zs=vertsZ, zdir='y')
def set_edgecolor(self, colors): PolyCollection.set_edgecolor(self, colors) self._edgecolor3d = PolyCollection.get_edgecolor(self)
def gen_land_bitmap(bmap, resolution_meters): #Get land polygons and bbox of polygons polys = [] xmin = np.finfo(np.float64).max xmax = -np.finfo(np.float64).max ymin = xmin ymax = xmax logging.debug('Rasterizing Basemap, number of land polys: ' + str(len(bmap.landpolygons))) # If no polys: return a zero map if (len(bmap.landpolygons) == 0): raise Exception('Basemap contains no land polys to rasterize') for polygon in bmap.landpolygons: coords = polygon.get_coords() xmin = min(xmin, np.min(coords[:, 0])) xmax = max(xmax, np.max(coords[:, 0])) ymin = min(ymin, np.min(coords[:, 1])) ymax = max(ymax, np.max(coords[:, 1])) polys.append(coords) xmin = np.floor(xmin / resolution_meters) * resolution_meters xmax = np.ceil(xmax / resolution_meters) * resolution_meters ymin = np.floor(ymin / resolution_meters) * resolution_meters ymax = np.ceil(ymax / resolution_meters) * resolution_meters # For debugging logging.debug('Rasterizing Basemap, bounding box: ' + str([xmin, xmax, ymin, ymax])) # Switch backend to prevent creating an empty figure in notebook orig_backend = plt.get_backend() plt.switch_backend('agg') # Create figure to help rasterize fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) # Set aspect and resolution # Aspect gives 1 in high plot aspect = (xmax - xmin) / (ymax - ymin) resolution_dpi = (ymax - ymin) / resolution_meters fig.set_dpi(resolution_dpi) fig.set_size_inches(aspect, 1) # Add polygons lc = PolyCollection(polys, facecolor='k', lw=0) ax.add_collection(lc) # Create canvas and rasterize canvas = FigureCanvasAgg(fig) try: canvas.draw() width, height = canvas.get_width_height() rgb_data = np.fromstring(canvas.tostring_rgb(), dtype='uint8').reshape(height, width, 3) data = rgb_data[:, :, 1] plt.close( fig ) #comment this for debugging purposes and replace with plt.show() logging.debug('Rasterized size: ' + str([width, height])) except MemoryError: gc.collect() raise Exception('Basemap rasterized size too large: ' + str(aspect * resolution_dpi) + '*' + str(resolution_dpi) + ' cells') finally: # Reset backend plt.switch_backend(orig_backend) return RasterizedBasemap(xmin, xmax, ymin, ymax, resolution_meters, data)
def plot_driver_states(self, driver_id, trip_count=50, start_time=0, fig_size=(30, 2), legend_size=6, xtick_size=10): driver_data = self.driver_actions.xs(driver_id, level=1).copy() driver_data.sort_values(by='assigned_time', inplace=True) trip_times = [] for i in driver_data[['assigned_time', 'driver_action', 'pickup_time', 'travel_time']].values: if i[1] == 1: assign_time = i[0] pickup_time = assign_time + i[2] drop_time = pickup_time + i[3] points = [assign_time, pickup_time, drop_time] trip_times.append(points) states = {'idle': 1, 'pick_up': 1, 'in_trip': 1} color_mapping = {"idle": "C0", "pick_up": "C1", "in_trip": "C2"} state_mapping = {0: "pick_up", 1: 'in_trip'} vertices = [] colors = [] end_time = start_time for t in trip_times[:trip_count]: if t[2] < end_time: continue v = [ (end_time, states['idle'] - 0.4), (end_time, states['idle'] + 0.4), (t[0], states['idle'] + 0.4), (t[0], states['idle'] - 0.4), (end_time, states['idle'] - 0.4), ] vertices.append(v) colors.append(color_mapping['idle']) for k in range(2): state = states[state_mapping[k]] v = [ (t[k], state - 0.4), (t[k], state + 0.4), (t[k + 1], state + 0.4), (t[k + 1], state - 0.4), (t[k], state - 0.4), ] vertices.append(v) colors.append(color_mapping[state_mapping[k]]) end_time = t[2] bars = PolyCollection(vertices, facecolors=colors) fig, ax = plt.subplots(figsize=fig_size) ax.add_collection(bars) ax.get_yaxis().set_visible(False) ax.autoscale() ax.tick_params(axis='x', which='major', labelsize=xtick_size) ax.tick_params(axis='x', which='minor', labelsize=xtick_size) idle = mpatches.Patch(color='C0', label='Idle time') pick_up = mpatches.Patch(color='C1', label='Pick up time') in_trip = mpatches.Patch(color='C2', label='Trip time') plt.legend(handles=[idle, pick_up, in_trip], bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0., prop={'size': legend_size}) plt.show()
ax.set_xlabel('Month') ax.set_xticks(np.arange(1, 13)) ax.set_ylabel('Year') ax.set_yticks(np.arange(2016, 2020)) ax.set_zlabel('Precipitation') # 绘制3D多边形 ax = fig.add_subplot(1, 2, 2, projection='3d') precipitation = [] for year in years: value = np.random.rand(len(month)) * 300 value[0], value[-1] = 0, 0 precipitation.append(list(zip(month, value))) poly = PolyCollection(precipitation, facecolors=['b', 'c', 'r', 'm']) poly.set_alpha(0.7) ax.add_collection3d(poly, zs=years, zdir='y') ax.set_xlabel('Month') ax.set_xlim3d(0, 12) ax.set_ylabel('Year') ax.set_ylim3d(2015, 2020) ax.set_zlabel('Precipitation') ax.set_zlim3d(0, 300) plt.show() # ### Axes3D # API:https://matplotlib.org/api/_as_gen/mpl_toolkits.mplot3d.axes3d.Axes3D.html # 本文涉及的绘制3D图形函数都位于此接口;
def set_facecolor(self, colors): PolyCollection.set_facecolor(self, colors) self._facecolors3d = PolyCollection.get_facecolor(self)
def set_verts(self, verts, closed=True): """Set 3D vertices.""" self.get_vector(verts) # 2D verts will be updated at draw time PolyCollection.set_verts(self, [], False) self._closed = closed
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 candlestick2_ohlc(ax, opens, highs, lows, closes, width=4, colorup='k', colordown='r', alpha=0.75, ): """Represent the open, close as a bar line and high low range as a vertical line. NOTE: this code assumes if any value open, low, high, close is missing they all are missing Parameters ---------- ax : `Axes` an Axes instance to plot to opens : sequence sequence of opening values highs : sequence sequence of high values lows : sequence sequence of low values closes : sequence sequence of closing values ticksize : int size of open and close ticks in points colorup : color the color of the lines where close >= open colordown : color the color of the lines where close < open alpha : float bar transparency Returns ------- ret : tuple (lineCollection, barCollection) """ _check_input(opens, highs, lows, closes) delta = width / 2. barVerts = [((i - delta, open), (i - delta, close), (i + delta, close), (i + delta, open)) for i, open, close in zip(xrange(len(opens)), opens, closes) if open != -1 and close != -1] rangeSegments = [((i, low), (i, high)) for i, low, high in zip(xrange(len(lows)), lows, highs) if low != -1] r, g, b = colorConverter.to_rgb(colorup) colorup = r, g, b, alpha r, g, b = colorConverter.to_rgb(colordown) colordown = r, g, b, alpha colord = {True: colorup, False: colordown, } colors = [colord[open < close] for open, close in zip(opens, closes) if open != -1 and close != -1] useAA = 0, # use tuple here lw = 0.5, # and here rangeCollection = LineCollection(rangeSegments, colors=((0, 0, 0, 1), ), linewidths=lw, antialiaseds=useAA, ) barCollection = PolyCollection(barVerts, facecolors=colors, edgecolors=((0, 0, 0, 1), ), antialiaseds=useAA, linewidths=lw, ) minx, maxx = 0, len(rangeSegments) miny = min([low for low in lows if low != -1]) maxy = max([high for high in highs if high != -1]) corners = (minx, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() # add these last ax.add_collection(rangeCollection) ax.add_collection(barCollection) return rangeCollection, barCollection
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')