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 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 colrboxy(cboxy, colrmap, marks, ncstr=0, nclrm=256): import numpy as np from matplotlib.collections import PolyCollection ## 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)
def set_data(self, zname, zdata, zcolor): if zdata!=None: if self.overall_plot_type=="polygon": 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) if self.overall_plot_type=="XY": if zname not in self.clts: clt = LineCollection(zdata)#, offsets=offs) clt.set_color(colors) #print dir(clt) self.clts[zname]=clt self.axe.add_collection(self.clts[zname], autolim=True) self.axe.autoscale_view() else: self.clts[zname].set_segments(zdata) if self.overall_plot_type=="img": if zname not in self.clts: axeimg=self.axe.imshow( Magvec, vmin=amin(Magvec), vmax=0.001, #amax(Magvec), aspect="auto", origin="lower", extent=[amin(yoko),amax(yoko), amin(freq),amax(freq)], #cmap='RdBu' ) self.fig.colorbar(axeimg)
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 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 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 plot_2D_cells(cells, axes): verts = np.array([cell.cube_map for cell in cells if cell.dim == 0]) / 2 edges = np.array([edge_vertices(cell) for cell in cells if cell.dim == 1]) faces = np.array([face_vertices(cell) for cell in cells if cell.dim == 2]) if verts.shape[0]: axes.scatter(verts[:, 1], verts[:, 0], marker='s') edges_coll = LineCollection(edges) edges_coll.set_color('green') edges_coll.set_linewidth(2) faces_coll = PolyCollection(faces, ) faces_coll.set_color('pink') axes.add_collection(edges_coll) axes.add_collection(faces_coll)
def plot_mic_patches(self, plotType, minConfidence): indx = self.snp[:, 9] >= minConfidence minsw = self.sw / float(2**self.snp[0, 4]) tsw1 = minsw * 0.5 tsw2 = -minsw * 0.5 * 3**0.5 ntri = len(self.snp) if plotType == 2: fig, ax = plt.subplots() if self.bpatches == False: xy = self.snp[:, :2] tmp = np.asarray([[tsw1] * ntri, (-1)**self.snp[:, 3] * tsw2]).transpose() tris = np.asarray([[[0, 0]] * ntri, [[minsw, 0]] * ntri, tmp]) self.patches = np.swapaxes(tris + xy, 0, 1) self.bpatches = True p = PolyCollection(self.patches[indx], cmap='viridis') p.set_array(self.color2[indx]) p.set_edgecolor('face') ax.add_collection(p) ax.set_xlim([-0.6, 0.6]) ax.set_ylim([-0.6, 0.6]) fig.colorbar(p, ax=ax) plt.show() if plotType == 1: fig, ax = plt.subplots() N = len(self.snp) mat = np.empty([N, 3, 3]) quat = np.empty([N, 4]) rod = np.empty([N, 3]) if self.bcolor1 == False: for i in range(N): mat[i, :, :] = RotRep.EulerZXZ2Mat(self.snp[i, 6:9] / 180.0 * np.pi) quat[i, :] = RotRep.quaternion_from_matrix(mat[i, :, :]) rod[i, :] = RotRep.rod_from_quaternion(quat[i, :]) self.color1 = (rod + np.array([1, 1, 1])) / 2 self.bcolor1 = True if self.bpatches == False: xy = self.snp[:, :2] tmp = np.asarray([[tsw1] * ntri, (-1)**self.snp[:, 3] * tsw2]).transpose() tris = np.asarray([[[0, 0]] * ntri, [[minsw, 0]] * ntri, tmp]) self.patches = np.swapaxes(tris + xy, 0, 1) self.bpatches = True p = PolyCollection(self.patches[indx], cmap='viridis') p.set_color(self.color1[indx]) ax.add_collection(p) ax.set_xlim([-0.6, 0.6]) ax.set_ylim([-0.6, 0.6]) plt.show()
def plot_cubical_2D_cell_complex(K): fig, axes = configure_2D_plot(K) verts = np.array([cell.cube_map for cell in K(0)]) / 2 edges = np.array([edge_vertices(cell) for cell in K(1)]) faces = np.array([face_vertices(cell) for cell in K(2)]) axes.scatter(verts[:, 1], verts[:, 0], alpha=0.5) edges_coll = LineCollection(edges) edges_coll.set_color('green') edges_coll.set_alpha(0.5) faces_coll = PolyCollection(faces, ) faces_coll.set_color('pink') axes.add_collection(edges_coll) axes.add_collection(faces_coll) return fig, axes
def plot_multi_lines(data): # plt.xlabel("State (cluster size)") # plt.ylabel("Q value (preference action)") # for k,v in data.items(): # plt.plot(v, label=k) # plt.legend() # plt.show() def polygon_under_graph(xlist, ylist): """ Construct the vertex list which defines the polygon filling the space under the (xlist, ylist) line graph. Assumes the xs are in ascending order. """ return [(xlist[0], -4.), *zip(xlist, ylist), (xlist[-1], -4.)] fig = plt.figure(figsize=(30, 20)) ax = fig.gca(projection='3d') # Make verts a list, verts[i] will be a list of (x,y) pairs defining polygon i verts = [] # Set up the x sequence xs = list(data.keys()) # The ith polygon will appear on the plane y = zs[i] zs = xs for i in zs: ys = data[i] verts.append(polygon_under_graph(xs, ys)) poly = PolyCollection(verts, alpha=.1, offsets=True) colours = [ colors.to_rgba(c) for c in plt.rcParams['axes.prop_cycle'].by_key()['color'] ] poly.set_color(colours) # poly.set_facecolor(colours) ax.add_collection3d(poly, zs=zs, zdir='y') ax.autoscale_view(scaley=True, scalez=True) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.set_xticks(range(0, 31)) ax.set_yticks(range(0, 31)) ax.set_xlim(0, 30) ax.set_ylim(0, 31) ax.set_zlim(-4, 4) plt.show()
def set_data(self, zname=None, zdata=None, zcolor=None, plot_type="poly"): if zdata!=None: if plot_type is "poly": if zname not in self.clts: #plottables['plotted']:#self.pd.list_data(): clt=PolyCollection([], alpha=0.5, antialiased=True)#, rasterized=False, antialiased=False) if zcolor is not None: clt.set_color(colorConverter.to_rgba(zcolor)) self.clts[zname]=clt self.axe.add_collection(self.clts[zname]) self.clts[zname].set_verts(zdata) elif plot_type is "line": if zname not in self.clts: clt=LineCollection(zdata)#, linewidths=(0.5, 1, 1.5, 2), #linestyles='solid', colors=("red", "blue", "green")) if zcolor is not None: clt.set_color(zcolor) else: clt.set_array(arange(len(zdata))) else: self.clts[zname].set_verts(zdata) #self.set_xlim(x.min(), x.max()) #self.set_ylim(ys.min(), ys.max()) elif plot_type is "scatter": self.axe.scatter(zdata, zdata) elif plot_type is "colormap": self.axe.pcolormesh(x, y, z) if 0: x = arange(3) ys = array([x + i for i in arange(5)]) #xdata=arange(len(getattr(self, zname))) data=[list(zip(x, y)) for y in ys] line_segments = LineCollection(data, linewidths=1, linestyles='solid', colors=mycolors) print data print len(data) #print line_segments.properties() #print line_segments.set_hatch("O") #print dir(self.axe) print [p.vertices for p in line_segments.get_paths()]#) print line_segments.get_segments()
class PolygonFormat(LineFormat): clt=Typed(PolyCollection) antialiased=Bool(True) def polygon_plot(self, *args, **kwargs): kwargs=process_kwargs(self, kwargs) #self.xdata=[arg[0] for arg in args[0][0]] #self.zdata=[[vert[1] for vert in line] for line in args[0]] self.clt=PolyCollection(args[0], alpha=self.alpha, antialiased=self.antialiased) self.clt.set_color(self.color) #from matplotlib.colors import colorConverter colorConverter.to_rgba( self.plotter.axes.add_collection(self.clt) def alter_xy(self, *args, **kwargs): self.color=kwargs.pop("color", self.color) zdata=args[0] self.clt.set_verts(zdata) self.clt.set_color(self.color)
def __plot_variance(self): pointsMin = self.__calc_min() pointsMax = self.__calc_max() polys = [] variance = [] varMin = 1000 varMax = 0 lastX = None lastYMin = None lastYMax = None for x in pointsMin.iterkeys(): if lastX is None: lastX = x if lastYMin is None: lastYMin = pointsMin[x] if lastYMax is None: lastYMax = pointsMax[x] polys.append([[x, pointsMin[x]], [x, pointsMax[x]], [lastX, lastYMax], [lastX, lastYMin], [x, pointsMin[x]]]) lastX = x lastYMin = pointsMin[x] lastYMax = pointsMax[x] var = pointsMax[x] - pointsMin[x] variance.append(var) varMin = min(varMin, var) varMax = max(varMax, var) norm = Normalize(vmin=varMin, vmax=varMax) sm = ScalarMappable(norm, self.colourMap) colours = sm.to_rgba(variance) pc = PolyCollection(polys) pc.set_gid('plot') pc.set_norm(norm) pc.set_color(colours) self.axes.add_collection(pc) return None, None
class PolygonFormat(LineFormat): clt = Typed(PolyCollection) antialiased = Bool(True) def polygon_plot(self, *args, **kwargs): kwargs = process_kwargs(self, kwargs) #self.xdata=[arg[0] for arg in args[0][0]] #self.zdata=[[vert[1] for vert in line] for line in args[0]] self.clt = PolyCollection(args[0], alpha=self.alpha, antialiased=self.antialiased) self.clt.set_color( self.color ) #from matplotlib.colors import colorConverter colorConverter.to_rgba( self.plotter.axes.add_collection(self.clt) def alter_xy(self, *args, **kwargs): self.color = kwargs.pop("color", self.color) zdata = args[0] self.clt.set_verts(zdata) self.clt.set_color(self.color)
def animate(p): global count, centers, angles, coords, extras, skip, colors, histogram, i, line2, success if (i >= n): i = 0 keep = True ax.cla() temp = move(centers[i]) tempa = turn(angles[i]) coords[n], coords2[n], extras[n], extras2[n] = chop(verts(temp, tempa)) xs = verts(temp, tempa)[:,0] if max(xs) > lenx or min(xs) < 0: keep = False else: for j in xrange(n): if j != i and touch(temp, centers[j], tempa, angles[j]): keep = False break count += 1 if keep: success += 1 colors[n] = tempc else: colors[n] = badc # for k in range(n+1): # for j in range(len(extras[k,:])): # lines = plot([extras[k,j-1,0], extras[k,j,0]], [extras[k,j-1,1], extras[k,j,1]], '--', color=colors[k], linewidth=2, alpha=alpha) # lines = plot([extras2[k,j-1,0], extras2[k,j,0]], [extras2[k,j-1,1], extras2[k,j,1]], '--', color=colors[k], linewidth=2, alpha=alpha) colors[i] = highlightc # swap things around so the moving triangles are always on top c = concatenate((coords, coords2), axis=0) c_extra = concatenate((extras, extras2), axis=0) cols = colors + colors swap = c[-2] swap_extra = c_extra[-2] c[-2] = c[n] c_extra[-2] = c_extra[n] c[n] = swap c_extra[n] = swap_extra swap = cols[-2] cols[-2] = cols[n] cols[n] = swap coll = PolyCollection(c) coll.set_color(cols) coll.set_alpha(alpha) coll_extra = PolyCollection(c_extra) coll_extra.set_color(cols) coll_extra.set_alpha(.2) #coll.set_color([cm.jet(x) for x in cols]) ax.collections=[] ax.add_collection(coll_extra) ax.add_collection(coll) ax.set_title("Attempted moves: %i, Successful moves: %i" %(count, success)) ax.axhline(y=0, linestyle='--', linewidth=3, color='b', zorder=1) ax.axhline(y=leny, linestyle='--', linewidth=3, color='orange', zorder=1) ax.axvline(x=0, linestyle='-', color='k', linewidth=3, zorder=1) ax.axvline(x=lenx, linestyle='-', color='k', linewidth=3, zorder=1) arlen = .5 arwidth = .5 delta = periodic_diff(centers[i], temp) for shift in [0, -leny, leny]: if shift == 0: aralpha = 1 else: aralpha = .5 line2 = ax.arrow(centers[i,0], centers[i,1]+shift, delta[0], delta[1], head_width=arwidth, head_length=arlen, linewidth=2, facecolor='slategray', zorder=3, alpha=aralpha) fig.tight_layout() if keep: centers[i] = temp angles[i] = tempa coords[i], coords2[i], extras[i], extras2[i] = chop(verts(centers[i], angles[i])) colors[i] = goodc else: colors[i] = rejectc if (i == n-1): colors = [defaultc]*(n+1) i += 1 return ax, line2
def plot_volume(sim, vol=None, center=None, size=None, options=None, plot3D=False, label=None): options = options if options else def_plot_options fig=plt.gcf() ax=fig.gca(projection='3d') if plot3D else fig.gca() if vol: center, size = vol.center, vol.size v0=np.array([center.x, center.y]) dx,dy=np.array([0.5*size.x,0.0]), np.array([0.0,0.5*size.y]) if plot3D: zmin,zmax = ax.get_zlim3d() z0 = zmin + options['zrel']*(zmax-zmin) ################################################## # add polygon(s) to the plot to represent the volume ################################################## def add_to_plot(c): ax.add_collection3d(c,zs=z0,zdir='z') if plot3D else ax.add_collection(c) if size.x==0.0 or size.y==0.0: # zero thickness, plot as line polygon = [ v0+dx+dy, v0-dx-dy ] add_to_plot( LineCollection( [polygon], colors=options['line_color'], linewidths=options['line_width'], linestyles=options['line_style'] ) ) else: if options['fill_color'] != 'none': # first copy: faces, no edges polygon = np.array([v0+dx+dy, v0-dx+dy, v0-dx-dy, v0+dx-dy]) pc=PolyCollection( [polygon], linewidths=0.0) pc.set_color(options['fill_color']) pc.set_alpha(options['alpha']) add_to_plot(pc) if options['boundary_width']>0.0: # second copy: edges, no faces closed_polygon = np.array([v0+dx+dy, v0-dx+dy, v0-dx-dy, v0+dx-dy, v0+dx+dy]) lc=LineCollection([closed_polygon]) lc.set_linestyle(options['boundary_style']) lc.set_linewidth(options['boundary_width']) lc.set_edgecolor(options['boundary_color']) add_to_plot(lc) ###################################################################### # attempt to autodetermine text rotation and alignment ###################################################################### if label: x0, y0, r, h, v = np.mean(ax.get_xlim()),np.mean(ax.get_ylim()), 0, 'center', 'center' if size.y==0.0: v = 'bottom' if center.y>y0 else 'top' elif size.x==0.0: r, h = (270,'left') if center.x>x0 else (90,'right') if plot3D: ax.text(center.x, center.y, z0, label, rotation=r, fontsize=options['fontsize'], color=options['line_color'], horizontalalignment=h, verticalalignment=v) else: ax.text(center.x, center.y, label, rotation=r, fontsize=options['fontsize'], color=options['line_color'], horizontalalignment=h, verticalalignment=v)
class QuiverKey(Artist): ''' Labelled arrow for use as a quiver plot scale key. ''' halign = {'N': 'center', 'S': 'center', 'E': 'left', 'W': 'right'} valign = {'N': 'bottom', 'S': 'top', 'E': 'center', 'W': 'center'} pivot = {'N': 'mid', 'S': 'mid', 'E': 'tip', 'W': 'tail'} def __init__(self, Q, X, Y, U, label, **kw): Artist.__init__(self) self.Q = Q self.X = X self.Y = Y self.U = U self.coord = kw.pop('coordinates', 'axes') self.color = kw.pop('color', None) self.label = label self.labelsep = T.Value(kw.pop('labelsep', 0.1)) * Q.ax.figure.dpi self.labelpos = kw.pop('labelpos', 'N') self.labelcolor = kw.pop('labelcolor', None) self.fontproperties = kw.pop('fontproperties', dict()) self.kw = kw self.text = Text(text=label, horizontalalignment=self.halign[self.labelpos], verticalalignment=self.valign[self.labelpos], fontproperties=FontProperties(**self.fontproperties)) if self.labelcolor is not None: self.text.set_color(self.labelcolor) self._initialized = False self.zorder = Q.zorder + 0.1 __init__.__doc__ = _quiverkey_doc def _init(self): if not self._initialized: self._set_transform() _pivot = self.Q.pivot self.Q.pivot = self.pivot[self.labelpos] self.verts = self.Q._make_verts(nx.array([self.U]), nx.zeros((1,))) self.Q.pivot = _pivot kw = self.Q.polykw kw.update(self.kw) self.vector = PolyCollection(self.verts, offsets=[(self.X,self.Y)], transOffset=self.get_transform(), **kw) if self.color is not None: self.vector.set_color(self.color) self.vector.set_transform(self.Q.get_transform()) self._initialized = True def _text_x(self, x): if self.labelpos == 'E': return x + self.labelsep.get() elif self.labelpos == 'W': return x - self.labelsep.get() else: return x def _text_y(self, y): if self.labelpos == 'N': return y + self.labelsep.get() elif self.labelpos == 'S': return y - self.labelsep.get() else: return y def draw(self, renderer): self._init() self.vector.draw(renderer) x, y = self.get_transform().xy_tup((self.X, self.Y)) self.text.set_x(self._text_x(x)) self.text.set_y(self._text_y(y)) self.text.draw(renderer) def _set_transform(self): if self.coord == 'data': self.set_transform(self.Q.ax.transData) elif self.coord == 'axes': self.set_transform(self.Q.ax.transAxes) elif self.coord == 'figure': self.set_transform(self.Q.ax.figure.transFigure) elif self.coord == 'inches': dx = ax.figure.dpi bb = T.Bbox(T.origin(), T.Point(dx, dx)) trans = T.get_bbox_transform(T.unit_bbox(), bb) self.set_transform(trans) else: raise ValueError('unrecognized coordinates') quiverkey_doc = _quiverkey_doc
def plot_mic_patches(self, plotType=1, minConfidence=0, maxConfidence=1, limitang=False, angles=[]): indx = [] for i in range(0, len(self.snp)): if self.snp[i, 9] >= minConfidence and self.snp[i, 9] <= maxConfidence: indx.append(i) if limitang: indx = self.angle_limiter(indx, self.snp, angles) else: indx = list(range(0, len(self.snp))) #indx=minConfidence<=self.snp[:,9]<=maxConfidence minsw = self.sw / float(2**self.snp[0, 4]) tsw1 = minsw * 0.5 tsw2 = -minsw * 0.5 * 3**0.5 ntri = len(self.snp) if plotType == 2: fig, ax = plt.subplots() if self.bpatches == False: xy = self.snp[:, :2] tmp = np.asarray([[tsw1] * ntri, (-1)**self.snp[:, 3] * tsw2]).transpose() tris = np.asarray([[[0, 0]] * ntri, [[minsw, 0]] * ntri, tmp]) self.patches = np.swapaxes(tris + xy, 0, 1) self.bpatches = True p = PolyCollection(self.patches[indx], cmap='viridis') p.set_array(self.color2[indx]) p.set_edgecolor('face') ax.add_collection(p) ax.set_xlim([-0.6, 0.6]) ax.set_ylim([-0.6, 0.6]) fig.colorbar(p, ax=ax) plt.show() if plotType == 1: fig, ax = plt.subplots() N = len(self.snp) mat = np.empty([N, 3, 3]) quat = np.empty([N, 4]) rod = np.empty([N, 3]) if self.bcolor1 == False: colors, maxangs, minangs = set_color_range( self, N, indx, mat, quat, rod) self.color1 = colors #print("Color: ", self.color1) #self.bcolor1=True if self.bpatches == False: xy = self.snp[:, :2] tmp = np.asarray([[tsw1] * ntri, (-1)**self.snp[:, 3] * tsw2]).transpose() tris = np.asarray([[[0, 0]] * ntri, [[minsw, 0]] * ntri, tmp]) self.patches = np.swapaxes(tris + xy, 0, 1) self.bpatches = True p = PolyCollection(self.patches[indx], cmap='viridis') p.set_color(self.color1[indx]) ax.add_collection(p) '''Yo future grayson, make sure interactive is a parameter!''' xmin = self.snp[indx[0], 0] xmax = self.snp[indx[0], 0] ymin = self.snp[indx[0], 1] ymax = self.snp[indx[0], 1] for i in indx: if self.snp[i, 0] <= xmin: xmin = self.snp[i, 0] if self.snp[i, 0] >= xmax: xmax = self.snp[i, 0] if self.snp[i, 1] <= ymin: ymin = self.snp[i, 1] if self.snp[i, 1] >= ymax: ymax = self.snp[i, 1] if abs(xmax - xmin) > abs(ymax - ymin): side_length = abs(xmax - xmin) else: side_length = abs(ymax - ymin) ax.set_xlim([xmin - .1, xmin + side_length + .1]) ax.set_ylim([ymin - .1, ymin + side_length + .1]) #note, previously, -.6<=x,y<=.6 voxels = VoxelClick(fig, self.snp, self.sw, self) voxels.connect() print("-------------------------------------------------") print("MaxRod (R,G,B): ", maxangs) print("MinRod (R,G,B): ", minangs) """write line here for adding text next to the plot""" """ maxs = ','.join(str(np.round_(x,decimals=4)) for x in maxangs) mins = ','.join(str(np.round_(x,decimals=4)) for x in minangs) plt.figtext(0.76, 0.5, "mins :"+maxs+"\nmaxes:"+mins) #plt.tight_layout() plt.gcf().subplots_adjust(right=0.75) #adjusting window for text to fit """ plt.show()
def plot_mic_patches(self, plotType, minConfidence, maxConfidence, indices): indx = [] for i in range(0, len(self.snp)): if self.snp[i, 9] >= minConfidence and self.snp[ i, 9] <= maxConfidence and i in indices: indx.append(i) #indx=minConfidence<=self.snp[:,9]<=maxConfidence minsw = self.sw / float(2**self.snp[0, 4]) tsw1 = minsw * 0.5 tsw2 = -minsw * 0.5 * 3**0.5 ntri = len(self.snp) if plotType == 2: fig, ax = plt.subplots() if self.bpatches == False: xy = self.snp[:, :2] tmp = np.asarray([[tsw1] * ntri, (-1)**self.snp[:, 3] * tsw2]).transpose() tris = np.asarray([[[0, 0]] * ntri, [[minsw, 0]] * ntri, tmp]) self.patches = np.swapaxes(tris + xy, 0, 1) self.bpatches = True p = PolyCollection(self.patches[indx], cmap='viridis') p.set_array(self.color2[indx]) p.set_edgecolor('face') ax.add_collection(p) ax.set_xlim([-0.6, 0.6]) ax.set_ylim([-0.6, 0.6]) fig.colorbar(p, ax=ax) plt.show() if plotType == 1: fig, ax = plt.subplots() N = len(self.snp) mat = np.empty([N, 3, 3]) quat = np.empty([N, 4]) rod = np.empty([N, 3]) if self.bcolor1 == False: maxr = 0.0 minr = 0.0 maxg = 0.0 ming = 0.0 maxb = 0.0 minb = 0.0 for i in range(N): if i in indx: mat[i, :, :] = RotRep.EulerZXZ2Mat(self.snp[i, 6:9] / 180.0 * np.pi) quat[i, :] = RotRep.quaternion_from_matrix( mat[i, :, :]) rod[i, :] = RotRep.rod_from_quaternion(quat[i, :]) if i == indx[0]: maxr = rod[i, 0] minr = rod[i, 0] maxg = rod[i, 1] ming = rod[i, 1] maxb = rod[i, 2] minb = rod[i, 2] else: if rod[i, 0] > maxr: maxr = rod[i, 0] elif rod[i, 0] < minr: minr = rod[i, 0] if rod[i, 1] > maxg: maxg = rod[i, 1] elif rod[i, 1] < ming: ming = rod[i, 1] if rod[i, 2] > maxb: maxb = rod[i, 2] elif rod[i, 2] < minb: minb = rod[i, 2] else: rod[i, :] = [0.0, 0.0, 0.0] print "Current rod values: ", rod maxrgb = [maxr, maxg, maxb] minrgb = [minr, ming, minb] colors = rod for j in range(N): for k in range(0, 3): colors[j, k] = (rod[j, k] - minrgb[k]) / (maxrgb[k] - minrgb[k]) self.color1 = colors print "Color: ", self.color1 #self.bcolor1=True if self.bpatches == False: xy = self.snp[:, :2] tmp = np.asarray([[tsw1] * ntri, (-1)**self.snp[:, 3] * tsw2]).transpose() tris = np.asarray([[[0, 0]] * ntri, [[minsw, 0]] * ntri, tmp]) self.patches = np.swapaxes(tris + xy, 0, 1) self.bpatches = True p = PolyCollection(self.patches[indx], cmap='viridis') p.set_color(self.color1[indx]) ax.add_collection(p) ax.set_xlim([-0.6, 0.6]) ax.set_ylim([-0.6, 0.6]) plt.show()
def set_data(self, zname=None, zdata=None, zcolor=None, plot_type="poly"): if zdata != None: if plot_type is "poly": if zname not in self.clts: #plottables['plotted']:#self.pd.list_data(): clt = PolyCollection( [], alpha=0.5, antialiased=True ) #, rasterized=False, antialiased=False) if zcolor is not None: clt.set_color(colorConverter.to_rgba(zcolor)) self.clts[zname] = clt self.axe.add_collection(self.clts[zname]) self.clts[zname].set_verts(zdata) elif plot_type is "line": if zname not in self.clts: clt = LineCollection( zdata) #, linewidths=(0.5, 1, 1.5, 2), #linestyles='solid', colors=("red", "blue", "green")) if zcolor is not None: clt.set_color(zcolor) else: clt.set_array(arange(len(zdata))) else: self.clts[zname].set_verts(zdata) #self.set_xlim(x.min(), x.max()) #self.set_ylim(ys.min(), ys.max()) elif plot_type is "scatter": self.axe.scatter(zdata, zdata) elif plot_type is "colormap": self.axe.pcolormesh(x, y, z) if 0: x = arange(3) ys = array([x + i for i in arange(5)]) #xdata=arange(len(getattr(self, zname))) data = [list(zip(x, y)) for y in ys] line_segments = LineCollection(data, linewidths=1, linestyles='solid', colors=mycolors) print data print len(data) #print line_segments.properties() #print line_segments.set_hatch("O") #print dir(self.axe) print[p.vertices for p in line_segments.get_paths()] #) print line_segments.get_segments() line_segments.set_array(arange(len(data))) x = arange(3) ys = array([x + i for i in arange(2)]) #xdata=arange(len(getattr(self, zname))) data = [list(zip(x, y)) for y in ys] line_segments.set_verts(data) #self.axe.add_collection(line_segments, autolim=True) clt = self.axe.scatter(x, x) #clt.set_linestyle("solid") print dir(clt) print clt.get_paths() if 0: #clt=QuadMesh(0, 0, [1]) n = 12 x = linspace(-1.5, 1.5, n) y = linspace(-1.5, 1.5, n * 2) X, Y = meshgrid(x, y) print X Qx = cos(Y) - cos(X) Qz = sin(Y) + sin(X) Qx = (Qx + 1.1) Z = sqrt(X**2 + Y**2) / 5 Z = (Z - Z.min()) / (Z.max() - Z.min()) Zm = ma.masked_where(fabs(Qz) < 0.5 * amax(Qz), Z) #ax = fig.add_subplot(121) #self.axe.set_axis_bgcolor("#bdb76b") clt = self.axe.pcolormesh(Z) #print dir(clt) self.axe.set_title('Without masked values')
def plot_volume(sim, vol=None, center=None, size=None, options=None, plot3D=False, label=None): options = options if options else def_plot_options fig = plt.gcf() ax = fig.gca(projection='3d') if plot3D else fig.gca() if vol: center, size = vol.center, vol.size v0 = np.array([center.x, center.y]) dx, dy = np.array([0.5 * size.x, 0.0]), np.array([0.0, 0.5 * size.y]) if plot3D: zmin, zmax = ax.get_zlim3d() z0 = zmin + options['zrel'] * (zmax - zmin) ################################################## # add polygon(s) to the plot to represent the volume ################################################## def add_to_plot(c): ax.add_collection3d(c, zs=z0, zdir='z') if plot3D else ax.add_collection(c) if size.x == 0.0 or size.y == 0.0: # zero thickness, plot as line polygon = [v0 + dx + dy, v0 - dx - dy] add_to_plot( LineCollection([polygon], colors=options['line_color'], linewidths=options['line_width'], linestyles=options['line_style'])) else: if options['fill_color'] != 'none': # first copy: faces, no edges polygon = np.array( [v0 + dx + dy, v0 - dx + dy, v0 - dx - dy, v0 + dx - dy]) pc = PolyCollection([polygon], linewidths=0.0) pc.set_color(options['fill_color']) pc.set_alpha(options['alpha']) add_to_plot(pc) if options['boundary_width'] > 0.0: # second copy: edges, no faces closed_polygon = np.array([ v0 + dx + dy, v0 - dx + dy, v0 - dx - dy, v0 + dx - dy, v0 + dx + dy ]) lc = LineCollection([closed_polygon]) lc.set_linestyle(options['boundary_style']) lc.set_linewidth(options['boundary_width']) lc.set_edgecolor(options['boundary_color']) add_to_plot(lc) ###################################################################### # attempt to autodetermine text rotation and alignment ###################################################################### if label: x0, y0, r, h, v = np.mean(ax.get_xlim()), np.mean( ax.get_ylim()), 0, 'center', 'center' if size.y == 0.0: v = 'bottom' if center.y > y0 else 'top' elif size.x == 0.0: r, h = (270, 'left') if center.x > x0 else (90, 'right') if plot3D: ax.text(center.x, center.y, z0, label, rotation=r, fontsize=options['fontsize'], color=options['line_color'], horizontalalignment=h, verticalalignment=v) else: ax.text(center.x, center.y, label, rotation=r, fontsize=options['fontsize'], color=options['line_color'], horizontalalignment=h, verticalalignment=v)
species_idx = 0 plt_range = numpy.arange(0, 800, 1) fig = plt.figure(1) data_TL = [] data_G = [] for result_idx in range(len(tl_args_list)): density_TL = stats.gaussian_kde(tl_results[result_idx][species_idx][1]) density_G = stats.gaussian_kde(g_results[result_idx][species_idx][1]) data_TL.append(list(zip(plt_range, density_TL(plt_range)))) data_G.append(list(zip(plt_range, density_G(plt_range)))) poly_TL = PolyCollection(data_TL) poly_TL.set_alpha(0.5) poly_TL.set_color('red') poly_G = PolyCollection(data_G) poly_G.set_alpha(0.5) poly_G.set_color('blue') ax = fig.gca(projection='3d') ax.set_xlabel('species_0') # ax.set_ylabel('time') ax.set_xlim3d(0, 800) ax.set_ylim3d(0, 7) ax.set_zlabel('proportion') ax.set_zlim3d(0, 0.015) ax.add_collection3d(poly_TL, zs=numpy.arange(1, 10, 1), zdir='y') ax.add_collection3d(poly_G, zs=numpy.arange(1, 10, 1), zdir='y')
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)
#### 3D Axes #### ax3d = fig.add_axes([.57,.22,.38,.38*winAspect], projection='3d') ax3d.set_xlabel('X') ax3d.set_ylabel('Z') # swap Y and Z ax3d.set_zlabel('Y') ax3d.set_xlim3d(-1, 1) ax3d.set_ylim3d(-1, 1) ax3d.set_zlim3d(1, -1) # Back plane verts3D = np.array([[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1],[-1,-1,1]]) vertsXY = [verts3D[:,:2]] vertsZ = verts3D[:,2] poly1 = PolyCollection(vertsXY) poly1.set_alpha(0.7) poly1.set_color('w') poly1.set_edgecolor('k') ax3d.add_collection3d(poly1, zs=vertsZ, zdir='y') # Front plane #verts3D = np.array([[-1,-1,-.95],[1,-1,-.95],[1,1,-.95],[-1,1,-.95],[-1,-1,-.95]]) verts3D = np.array([[-1,-1,-1],[1,-1,-1],[1,1,-1],[-1,1,-1],[-1,-1,-1]]) vertsXY = [verts3D[:,:2]] vertsZ = verts3D[:,2] poly2 = PolyCollection(vertsXY) poly2.set_alpha(0.7) poly2.set_color('w') poly2.set_edgecolor('k') ax3d.add_collection3d(poly2, zs=vertsZ, zdir='y')
depth = min(depth, slider1.valmax) slider1.set_val(depth) if (event.inaxes is playButt4): for d in np.arange(-2, 2, .1): depth = d update(depth) slider1.set_val(depth) fig.canvas.mpl_connect('button_press_event', on_playButt) # 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.2) poly1.set_color('w') poly1.set_edgecolor('k') ax3d.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.5) poly2.set_color('w') poly2.set_edgecolor('k') ax3d.add_collection3d(poly2, zs=vertsZ, zdir='y') # Necker Radiobuttons rax = plt.axes([0.005, 0.25, 0.16/winAspect, 0.4])
ax.set_xlabel('X') ax.set_ylabel('Z') # swap Y and Z ax.set_zlabel('Y') ax.set_xlim3d(-1, 1) ax.set_ylim3d(-1, 1) ax.set_zlim3d(-1, 1) #### Polygon1 #### # 2D [[x,y]...] and 1D [z...] verts1 = [[[-1,-1], [1., -1], [1., 1.], [-1, 1.], [-1,-1]]] poly1 = PolyCollection(verts1) poly1.set_alpha(0.7) poly1.set_color('r') zs=[-1,-1,1,1,-1] ax.add_collection3d(poly1, zs=zs, zdir='y') #### Polygon2 #### # 3D [[x,y,z]...] list verts3D = np.array([[-1,-1,0],[1,-1,0],[1,1,0],[-1,1,0],[-1,-1,0]]) # Split 3D [[x,y,z]...] list into 2D [[x,y]...] and 1D [z...] vertsXY = [[[verts3D[i][0], verts3D[i][1]] for i in range(len(verts3D))]] vertsZ = [ verts3D[i][2] for i in range(len(verts3D))] poly2 = PolyCollection(vertsXY) poly2.set_alpha(0.7) poly2.set_color('g') ax.add_collection3d(poly2, zs=vertsZ, zdir='y')
def plot_subregion(sim, vol=None, center=None, size=None, plot3D=False, label=None, section=None, options=None): """ Add polygons representing subregions of meep geometries to the current 2D or 3D geometry visualization. """ #--------------------------------------------------------------- #- fetch values of relevant options for the specified section #-------------------------------------------------------------- keys = [ 'linecolor', 'linewidth', 'linestyle', 'fillcolor', 'alpha', 'fontsize', 'zmin', 'latex' ] vals = vis_opts(keys, section=section, overrides=options) linecolor, linewidth, linestyle, fillcolor = vals[0:4] alpha, fontsize, zbar, latex = vals[4:8] fig = plt.gcf() ax = fig.gca(projection='3d') if plot3D else fig.gca() #-------------------------------------------------------------- # unpack subregion geometry #-------------------------------------------------------------- if vol: center, size = vol.center, vol.size v0 = np.array([center[0], center[1]]) dx, dy = np.array([0.5 * size[0], 0.0]), np.array([0.0, 0.5 * size[1]]) if plot3D: zmin, zmax = ax.get_zlim3d() z0 = 0.0 #-------------------------------------------------------------- # add polygon(s) to the plot to represent the volume #-------------------------------------------------------------- def add_to_plot(c): ax.add_collection3d(c, zs=z0, zdir='z') if plot3D else ax.add_collection(c) if size[0] == 0.0 or size[1] == 0.0: #======================================== # region has zero thickness: plot as line #======================================== polygon = [v0 + dx + dy, v0 - dx - dy] add_to_plot( LineCollection([polygon], colors=linecolor, linewidths=linewidth, linestyles=linestyle)) else: #======================================== # plot as polygon, with separate passes # for the perimeter and the interior #======================================== if fillcolor: # first copy: faces, no edges polygon = np.array( [v0 + dx + dy, v0 - dx + dy, v0 - dx - dy, v0 + dx - dy]) pc = PolyCollection([polygon], linewidths=0.0) pc.set_color(fillcolor) pc.set_alpha(alpha) add_to_plot(pc) if linewidth > 0.0: # second copy: edges, no faces closed_polygon = np.array([ v0 + dx + dy, v0 - dx + dy, v0 - dx - dy, v0 + dx - dy, v0 + dx + dy ]) lc = LineCollection([closed_polygon]) lc.set_linestyle(linestyle) lc.set_linewidth(linewidth) lc.set_edgecolor(linecolor) add_to_plot(lc) ##################################################################### if label and fontsize > 0: plt.rc('text', usetex=latex) if latex: label = label.replace('_', '\_') x0, y0, r, h, v = np.mean(ax.get_xlim()), np.mean( ax.get_ylim()), 0, 'center', 'center' if size[1] == 0.0: v = 'bottom' if center[1] > y0 else 'top' elif size[0] == 0.0: r, h = (270, 'left') if center[0] > x0 else (90, 'right') if plot3D: ax.text(center[0], center[1], z0, label, rotation=r, fontsize=fontsize, color=linecolor, horizontalalignment=h, verticalalignment=v) else: ax.text(center[0], center[1], label, rotation=r, fontsize=fontsize, color=linecolor, horizontalalignment=h, verticalalignment=v)
def animate(p): global count, centers, angles, coords, extras, skip, colors, histogram, i, line2, success if (i >= n): i = 0 keep = True ax.cla() temp = move(centers[i]) tempa = turn(angles[i]) coords[n], coords2[n], extras[n], extras2[n] = chop(verts(temp, tempa)) xs = verts(temp, tempa)[:, 0] if max(xs) > lenx or min(xs) < 0: keep = False else: for j in xrange(n): if j != i and touch(temp, centers[j], tempa, angles[j]): keep = False break count += 1 if keep: success += 1 colors[n] = tempc else: colors[n] = badc # for k in range(n+1): # for j in range(len(extras[k,:])): # lines = plot([extras[k,j-1,0], extras[k,j,0]], [extras[k,j-1,1], extras[k,j,1]], '--', color=colors[k], linewidth=2, alpha=alpha) # lines = plot([extras2[k,j-1,0], extras2[k,j,0]], [extras2[k,j-1,1], extras2[k,j,1]], '--', color=colors[k], linewidth=2, alpha=alpha) colors[i] = highlightc # swap things around so the moving triangles are always on top c = concatenate((coords, coords2), axis=0) c_extra = concatenate((extras, extras2), axis=0) cols = colors + colors swap = c[-2] swap_extra = c_extra[-2] c[-2] = c[n] c_extra[-2] = c_extra[n] c[n] = swap c_extra[n] = swap_extra swap = cols[-2] cols[-2] = cols[n] cols[n] = swap coll = PolyCollection(c) coll.set_color(cols) coll.set_alpha(alpha) coll_extra = PolyCollection(c_extra) coll_extra.set_color(cols) coll_extra.set_alpha(.2) #coll.set_color([cm.jet(x) for x in cols]) ax.collections = [] ax.add_collection(coll_extra) ax.add_collection(coll) ax.set_title("Attempted moves: %i, Successful moves: %i" % (count, success)) ax.axhline(y=0, linestyle='--', linewidth=3, color='b', zorder=1) ax.axhline(y=leny, linestyle='--', linewidth=3, color='orange', zorder=1) ax.axvline(x=0, linestyle='-', color='k', linewidth=3, zorder=1) ax.axvline(x=lenx, linestyle='-', color='k', linewidth=3, zorder=1) arlen = .5 arwidth = .5 delta = periodic_diff(centers[i], temp) for shift in [0, -leny, leny]: if shift == 0: aralpha = 1 else: aralpha = .5 line2 = ax.arrow(centers[i, 0], centers[i, 1] + shift, delta[0], delta[1], head_width=arwidth, head_length=arlen, linewidth=2, facecolor='slategray', zorder=3, alpha=aralpha) fig.tight_layout() if keep: centers[i] = temp angles[i] = tempa coords[i], coords2[i], extras[i], extras2[i] = chop( verts(centers[i], angles[i])) colors[i] = goodc else: colors[i] = rejectc if (i == n - 1): colors = [defaultc] * (n + 1) i += 1 return ax, line2