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 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 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 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 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 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 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 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 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 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 _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 plot_multiple_timeseries(windpark, show=True): """Plot multiple power series of some turbines. Parameters ---------- windpark : Windpark A given windpark to plot power series. """ X = np.array(windpark.get_powermatrix()) number_turbines = len(X[0]) number_measurements = len(X) length = 100 X = X[:length] fig = plt.figure() ax = fig.gca(projection='3d') # cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6) def cc(arg): return colorConverter.to_rgba(arg, alpha=0.6) xs = range(1, number_measurements) verts = [] zs = range(0, number_turbines) for z in zs: ys = X[:, z] 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'), cc('g'), cc('b')]) poly.set_alpha(0.7) ax.add_collection3d(poly, zs=zs, zdir='y') ax.set_xlabel('Time') ax.set_xlim3d(0, length) ax.set_ylabel('Turbine') ax.set_ylim3d(-1, number_turbines) ax.set_zlabel('Power') ax.set_zlim3d(0, 30.) plt.title("Time Series Comparison") if show: plt.show()
def plot_population(ivp, depv_z_map): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') verts=[] nt = 1000 t = np.linspace(ivp.indepv_out()[0], ivp.indepv_out()[-1], nt) n = len(depv_z_map) maxval = 0 # Get interpolated (and back-transformed) results tm = time.time() for depv, x in depv_z_map.items(): interpol = ivp.get_interpolated(t, [depv]) # Let polygons be aligned with bottom # (important: choose nt large!) interpol[0,0] = 0.0 interpol[0,-1] = 0.0 # Check fo new max value: maxval = max(maxval, np.max(interpol)) stacked = zip(t,interpol.reshape(nt)) verts.append(stacked)#.transpose()) print("Time of interpolation and back transformation: {}".format( time.time()-tm)) # Generate plot tm = time.time() poly = PolyCollection(verts, facecolors = [ 'rgbk'[i%4] for i in range(len(verts))]) poly.set_alpha(0.7) ax.add_collection3d(poly, zs=[ x+1 for x in depv_z_map.values()], zdir='y') ax.set_xlabel('t') ax.set_xlim3d(0, t[-1]) ax.set_ylabel('y') ax.set_ylim3d(0.5, n+0.5) ax.set_zlabel('z') ax.set_zlim3d(0, maxval) ya = ax.get_yaxis() ya.set_major_locator(MaxNLocator(integer=True)) print ("Time of plot generation: {}".format(time.time()-tm)) plt.show()
def poly_plot(verts,cmap=None,sampled=None,view_angles=[10,270],outdir='./',outname='vert_',sampling=10,format='eps'): plt.figure() ax = plt.gca(projection='3d') if cmap is not None: poly = PolyCollection(verts[::sampling],facecolors=cmap[::sampling]) else: poly = PolyCollection(verts[::sampling]) poly.set_alpha(0.7) poly.set_edgecolor('none') ax.add_collection3d(poly, zs=sampled[:,0], zdir='y') if sampled is not None: tticks = np.arange(0,sampled[:,0].max()+1,sampled[:,0].max()/2) xticks = np.arange(0,301,100) zticks = np.arange(0,sampled[:,6].max()+1,sampled[:,6].max()/2) ax.set_yticks(tticks) ax.set_xticks(xticks) ax.set_xlim3d(0, 300.0) ax.set_ylim3d(0, sampled[:,0].max()) ax.set_zlim3d(0, sampled[:,6].max()) ax.set_xlabel('$x$',linespacing=3.2) ax.set_ylabel('$t$',linespacing=3.2) ax.set_zlabel('$I$',linespacing=3.2) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') ax.zaxis.set_ticks_position('none') ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0)) plt.draw() for v,view in enumerate(view_angles): ax.view_init(elev=view[0], azim=view[1]) fig_name = outname+str(view[0])+'_'+str(view[1]) plt.savefig(os.path.join(outdir,fig_name+'.'+format),format=format,dpi=320,bbox_inches='tight') return
def make_3d_plot(ax, xs, y, zs, colors): # make areas verts = [] verts_sem = [] for ii in range(y.shape[2]): ys = np.mean(y[:, :, ii], axis=0) verts.append(list(zip(np.hstack((0., xs, 1.)), np.hstack((0., ys, 0.))))) ys += np.std(y[:, :, ii], axis=0) / np.sqrt(len(subjects)) verts_sem.append(list(zip(np.hstack((0., xs, 1.)), np.hstack((0., ys, 0.))))) poly = PolyCollection(verts, facecolors=colors, edgecolor='k', linewidth=1) poly.set_alpha(.75) ax.add_collection3d(poly, zs=zs, zdir='y') poly = PolyCollection(verts_sem, facecolors=colors, edgecolor='none') poly.set_alpha(0.5) ax.add_collection3d(poly, zs=zs, zdir='y') return pretty_plot(ax)
def density_plot(): fig = plt.figure() ax = fig.gca(projection='3d') a, b = (np.log(0.2), np.log(4)) #a, b = (0.1, 4) gs = 41 # grid size xs = np.linspace(a, b, gs) bm = bm_model.BM() num_rhos = 12 rhos = np.linspace(0.945, 0.99, num_rhos) greys = np.linspace(0.3, 0.7, num_rhos) init, n = 5, 50000 Y = np.empty(n) verts = [] for rho in rhos: bm.rho = rho sigma = get_policy(bm, tol=0.05) Y[0] = init W = bm.shocks(n) for t in range(n-1): Y[t+1] = bm.f(sigma(Y[t]), W[t]) print rho, np.mean(Y) Y = np.log(Y) ys = np.empty(gs - 1) for i in range(gs - 1): ys[i] = np.sum((xs[i] <= Y) * (Y < xs[i+1])) / n ys[0], ys[-1] = 0, 0 verts.append(zip(xs, ys)) poly = PolyCollection(verts, facecolors = [str(g) for g in greys]) poly.set_alpha(0.85) ax.add_collection3d(poly, zs=rhos, zdir='x') ax.text(np.mean(rhos), a-1.4, -0.02, r'$\beta$', fontsize=16) ax.text(np.max(rhos)+0.016, (a+b)/2, -0.02, r'$\log(y)$', fontsize=16) ax.set_ylim3d(-1.5, 1.5) ax.set_xlim3d(rhos[0], rhos[num_rhos-1]) ax.set_zlim3d(0, 0.15) ax.set_zticks((0.15,)) plt.show()
def ThreeD(): fig = plt.figure() ax = Axes3D(fig) 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(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_xlim3d(0, 10) ax.set_ylim3d(-1, 4) ax.set_zlim3d(0, 1) plt.show()
def fiveDaysProfilePlugin(): """ Gráfico de área do perfil diário médio da variável a partir de dados de 5 dias. Dados devem corresponder a uma consulta de 5 dias (úteis) com valores médios a cada hora. """ if len(ep.EpmDatasetPens.SelectedPens) != 1: ep.showMsgBox('EPM Python Plugin - Demo Power', 'Please select a single pen before applying this function!', 'Warning') return 0 def cc(arg): return colorConverter.to_rgba(arg, alpha=0.6) epmDataValue = ep.EpmDatasetPens.SelectedPens[0].Values['Value'] epmAvg = np.vstack((epmDataValue[0:24], epmDataValue[24:2*24], epmDataValue[2*24:3*24], epmDataValue[3*24:4*24], epmDataValue[4*24:5*24])) epmAvg = epmAvg.mean(axis=0) epmAvg[0], epmAvg[-1] = 0,0 ys = np.arange(1, 25) zs = [0., 1., 2., 3., 4., 5.] profileList = [] profileList.append( list(zip(ys, epmAvg))) ini = 0 end = 24 for i in range(5): dataPeriod = epmDataValue[ini:end] dataPeriod[0], dataPeriod[-1] = 0,0 profileList.append( list(zip(ys, dataPeriod))) ini += 24 end += 24 poly = PolyCollection(profileList, facecolors=[cc('k'), cc('r'), cc('g'), cc('b'), cc('y'), cc('c')]) fig = plt.figure(figsize=(15, 8)) ax = fig.gca(projection='3d') poly.set_alpha(0.7) ax.add_collection3d(poly, zs=zs, zdir='y') ax.set_xlabel('hour') ax.set_xlim3d(1, 24) ax.set_ylabel('day') ax.set_ylim3d(-1, 6) ax.set_zlabel('power') ax.set_zlim3d(epmDataValue.min(), epmDataValue.max()) plt.show()
def plot_surf( vertices, faces, overlay, rotate=[270, 90], cmap='viridis', filename='plot.png', label=False, vmax=None, vmin=None, x_rotate=270, pvals=None, colorbar=True, cmap_label='value', title=None, mask=None, base_size=6, arrows=None, arrow_subset=None, arrow_size=0.5, arrow_colours=None, arrow_head=0.05, arrow_width=0.001, alpha_colour=None, flat_map=False, z_rotate=0, parcel=None, parcel_cmap=None, ): """ This function plot mesh surface with a given overlay. Features available : display in flat surface, display parcellation on top, display gradients arrows on top Parameters: ---------- vertices : numpy array vertex locations faces : numpy array triangles of vertex indices definings faces overlay : numpy array array to be plotted rotate : tuple, optional rotation angle for lateral on lh, and medial cmap : string, optional matplotlib colormap filename : string, optional name of the figure to save label : bool, optional colours smoothed (mean) or median if label vmin, vmax : float, optional min and max value for display intensity x_rotate : int, optional pvals : bool, optional colorbar : bool, optional display or not colorbar cmap_label : string, optional label of the colorbar title : string, optional title of the figure mask : numpy array, optional vector to mask part of the surface base_size : int, optional arrows : numpy array, optional dipsplay arrows in the directions of gradients on top of the surface arrow_subset : numpy array, optional vector containing at which vertices display an arrow arrow_size : float, optional size of the arrow arrow_colours: alpha_colour : float, optional value to play with transparency of the overlay flat_map : bool, optional display on flat map z_rotate : int, optional parcel : numpy array, optional delineate rois on top of the surface parcel_cmap : dictionary, optional dic containing labels and colors associated for the parcellation """ vertices = vertices.astype(np.float) F = faces.astype(int) vertices = (vertices - (vertices.max(0) + vertices.min(0)) / 2) / max(vertices.max(0) - vertices.min(0)) if not isinstance(rotate, list): rotate = [rotate] if not isinstance(overlay, list): overlays = [overlay] else: overlays = overlay if flat_map: z_rotate = 90 rotate = [90] intensity = np.ones(len(F)) else: #change light source if z is rotate light = np.array([0, 0, 1, 1]) @ yrotate(z_rotate) intensity = shading_intensity(vertices, F, light=light[:3], shading=0.7) #make figure dependent on rotations fig = plt.figure(figsize=(base_size * len(rotate) + colorbar * (base_size - 2), (base_size - 1) * len(overlays))) if title is not None: plt.title(title, fontsize=25) plt.axis('off') for k, overlay in enumerate(overlays): #colours smoothed (mean) or median if label if label: colours = np.median(overlay[F], axis=1) else: colours = np.mean(overlay[F], axis=1) if vmax is not None: colours = (colours - vmin) / (vmax - vmin) colours = np.clip(colours, 0, 1) else: colours = (colours - colours.min()) / (colours.max() - colours.min()) vmax = colours.max() vmin = colours.min() C = plt.get_cmap(cmap)(colours) if alpha_colour is not None: C = adjust_colours_alpha(C, np.mean(alpha_colour[F], axis=1)) if pvals is not None: C = adjust_colours_pvals(C, pvals, F, mask) elif mask is not None: C = mask_colours(C, F, mask) if parcel is not None: C = add_parcelation_colours(C, parcel, F, parcel_cmap, mask) #adjust intensity based on light source here C[:, 0] *= intensity C[:, 1] *= intensity C[:, 2] *= intensity for i, view in enumerate(rotate): MVP = perspective(25, 1, 1, 100) @ translate(0, 0, -3) @ yrotate( view) @ zrotate(z_rotate) @ xrotate(x_rotate) @ zrotate( 270 * flat_map) #translate coordinates based on viewing position V = np.c_[vertices, np.ones(len(vertices))] @ MVP.T V /= V[:, 3].reshape(-1, 1) center = np.array([0, 0, 0, 1]) @ MVP.T center /= center[3] # add vertex positions to A_dir before transforming them if arrows is not None: #calculate arrow position + small shift in surface normal direction vertex_normal_orig = vertex_normals(vertices, faces) A_base = np.c_[vertices + vertex_normal_orig * 0.01, np.ones(len(vertices))] @ MVP.T A_base /= A_base[:, 3].reshape(-1, 1) #calculate arrow direction A_dir = np.copy(arrows) #normalise arrow size max_arrow = np.max(np.linalg.norm(arrows, axis=1)) A_dir = arrow_size * A_dir / max_arrow A_dir = np.c_[A_dir, np.ones(len(A_dir))] @ MVP.T A_dir /= A_dir[:, 3].reshape(-1, 1) # A_dir *= 0.1; V = V[F] #triangle coordinates T = V[:, :, :2] #get Z values for ordering triangle plotting Z = -V[:, :, 2].mean(axis=1) #sort the triangles based on their z coordinate. If front/back views then need to sort a different axis front, back = frontback(T) T = T[front] s_C = C[front] Z = Z[front] I = np.argsort(Z) T, s_C = T[I, :], s_C[I, :] ax = fig.add_subplot(len(overlays), len(rotate) + 1, 2 * k + i + 1, xlim=[-.98, +.98], ylim=[-.98, +.98], aspect=1, frameon=False, xticks=[], yticks=[]) collection = PolyCollection(T, closed=True, linewidth=0, antialiased=False, facecolor=s_C) collection.set_alpha(1) ax.add_collection(collection) #add arrows to image if arrows is not None: front_arrows = F[front].ravel() for arrow_index, i in enumerate(arrow_subset): if i in front_arrows and A_base[i, 2] < center[2] + 0.01: arrow_colour = 'k' if arrow_colours is not None: arrow_colour = arrow_colours[arrow_index] #if length of arrows corresponds perfectly with coordinates # assume 1:1 matching if len(A_dir) == len(A_base): direction = A_dir[i] #otherwise, assume it is a custom list matching the elif len(A_dir) == len(arrow_subset): direction = A_dir[arrow_index] half = direction * 0.5 ax.arrow(A_base[i, 0] - half[0], A_base[i, 1] - half[1], direction[0], direction[1], head_width=arrow_head, width=arrow_width, color=arrow_colour) # ax.arrow(A_base[idx,0], A_base[idx,1], A_dir[i,0], A_dir[i,1], head_width=0.01) plt.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0) if colorbar: l = 0.7 if len(rotate) == 1: l = 0.5 cbar_size = [l, 0.3, 0.03, 0.38] cbar = fig.colorbar(cm.ScalarMappable(cmap=cmap), ticks=[0, 0.5, 1], cax=fig.add_axes(cbar_size)) cbar.ax.set_yticklabels([ np.round(vmin, decimals=2), np.round(np.mean([vmin, vmax]), decimals=2), np.round(vmax, decimals=2) ]) cbar.ax.tick_params(labelsize=25) cbar.ax.set_title(cmap_label, fontsize=25, pad=30) if filename is not None: fig.savefig(filename, bbox_inches='tight', pad_inches=0, transparent=True) return
def waterfall_plot(x, y, z, x_label="", y_label="", z_label="", use_poly=True, alpha=0.2, filename="", y_range=None, x_range=None): """ :param Dvector x: First axis :param Dvector y: Second axis :param Dvector z: Third axis :param string x_label: Label for first axis :param string y_label: Label for second axis :param string z_label: Label for third axis :param bool use_poly: Whether to use filled polygons :param double alpha: Set transparency of filled polygons :param string filename: Location to save file. If "", use interactive plot :param Dvector y_range: Change range of second axis if not None :param Dvector x_range: Change range of first axis if not None Generate a waterfall plot. """ print "\nGenerating waterfall_plot..." plt.clf() fig = plt.figure() ax = fig.gca(projection='3d') data = [zip(x, y[n]) for n, z_n in enumerate(z)] if use_poly: from matplotlib.collections import PolyCollection # Parameter closed MUST be set False if axis does not start at zero: curves = PolyCollection(data, closed=False) else: from matplotlib.collections import LineCollection curves = LineCollection(data) curves.set_alpha(alpha) ax.add_collection3d(curves, zs=z, zdir='y') ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.set_zlabel(z_label) if x_range is None: ax.set_xlim3d(x[0], x[-1]) else: ax.set_xlim3d(x_range) # Note the use of z as a parameter for ylim and also the reverse: ax.set_ylim3d(z[0], z[-1]) if y_range is not None: ax.set_zlim3d(y_range) # Avoid overlapping axis text: plt.tight_layout() if filename: plt.savefig(filename) print "Wrote file", filename else: plt.show()
def plotHistogram3D(self, temp_cells, meanGFP=1, minGFP=0, maxGFP=100, numBins=100, dirName=''): fig = P.figure(num=None, figsize=(8, 8), dpi=300, facecolor='w', edgecolor='k') ax = fig.add_subplot(111, projection='3d') font = {'family': 'Arial', 'weight': 'normal', 'size': 12} P.rc('font', **font) temperatures = [29, 31, 33, 35, 37] colors = cycle(["#feedde", "#fdbe85", "#fd8d3c", "#e6550d", "#a63603"]) cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6) verts = [] for z, cells in zip(temperatures, temp_cells): GFPs = [] for cell in cells: GFPs.extend(cell.GFP[:]) GFPs = [gfp - meanGFP for gfp in GFPs] #Subtract background GFPs = N.log10(GFPs) maxGFP = 2. ####TEMP minGFP = N.min(GFPs) bins = N.arange(minGFP - meanGFP, maxGFP - meanGFP, (maxGFP - minGFP) / numBins) #n, bins, patches = P.hist(GFPs, bins, normed=1, histtype='stepfilled') #@UnusedVariable histo, bin_edges = N.histogram(GFPs, bins, density=True) xs = bins[:-1] ys = histo # #ax.plot(xs, N.ones(xs.shape)*z, ys, color="red", alpha=.2) c = next(colors) ax.bar(xs, ys, zs=z, zdir='y', color=c, edgecolor='black', alpha=0.9, width=(maxGFP - minGFP) / numBins) ax.view_init(elev=16., azim=-56.) verts.append(list(zip(xs, ys))) poly = PolyCollection(verts, facecolors=[ cc("Yellow"), cc("Orange"), cc("OrangeRed"), cc("Red"), cc("DarkRed") ], closed=False) poly.set_alpha(.9) #ax.add_collection3d(poly, zs=temperatures, zdir='y') ax.set_yticks(temperatures) ax.set_xlabel('GFP intensity (log10 scale)', fontsize=14) ax.set_ylabel('Temperature ($^\circ$C)', fontsize=14) ax.set_zlabel('Probability density', fontsize=14) if len(dirName) > 0: fileName = dirName + 'histogram_temperature.pdf' P.savefig(fileName) else: P.show()
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')
def plotHistogram3Dsim(self, simGFPs, meanGFP=1, minGFP=0, maxGFP=100, numBins=100, dirName=''): fig = P.figure(num=None, figsize=(8, 8), dpi=300, facecolor='w', edgecolor='k') ax = fig.add_subplot(111, projection='3d') font = {'family': 'Arial', 'weight': 'normal', 'size': 12} P.rc('font', **font) temperatures = [.12, .14, .16, .18, .2] colors = cycle(["#feedde", "#fdbe85", "#fd8d3c", "#e6550d", "#a63603"]) verts = [] cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6) for z, GFPs in zip(temperatures, simGFPs): #GFPs=[] #for cell in cells: # GFPs.extend(cell.GFP[:]) #GFPs=[gfp-meanGFP for gfp in GFPs] #Subtract background # GFPs = N.log10(GFPs) bins = N.arange(minGFP - meanGFP, maxGFP - meanGFP, (maxGFP - minGFP) / numBins) #n, bins, patches = P.hist(GFPs, bins, normed=1, histtype='stepfilled') #@UnusedVariable histo, bin_edges = N.histogram(GFPs, bins, density=True) xs = bins[:-1] ys = histo #xs = N.arange(20) #ys = N.random.rand(20) # You can provide either a single color or an array. To demonstrate this, # the first bar of each set will be colored cyan. #cs = [c] * len(xs) #cs[0] = 'c' #ax.bar(xs, ys, zs=z, zdir='y', color=next(colors), alpha=0.7, width=(maxGFP-minGFP)/numBins) ax.plot(xs, N.ones(xs.shape) * z, ys, color="black", alpha=.2) #ax.fill_between(xs, N.ones(xs.shape)*z, ys, alpha=.5, antialiased=True, color=next(colors)) ax.view_init(elev=16., azim=-56.) verts.append(list(zip(xs, ys))) poly = PolyCollection(verts, facecolors=[ cc("#feedde"), cc("#fdbe85"), cc("#fd8d3c"), cc("#e6550d"), cc("#a63603") ]) poly.set_alpha(.9) ax.add_collection3d(poly, zs=temperatures, zdir='y') ax.set_yticks(temperatures) ax.set_xlabel('FliAZ (log10 scale)', fontsize=14) ax.set_ylabel('Noise intensity ($\Omega$)', fontsize=14) ax.set_zlabel('Probability density', fontsize=14) # ax.set_zlim((0.02, 0.32)) if len(dirName) > 0: fileName = dirName + 'histogram_noise.pdf' P.savefig(fileName) else: P.show()
def candlestick( self, ax, opens, highs, lows, closes, width=4, colorup='g', colordown='r', alpha=0.75, ): delta = width / 2. barVerts = [((i - delta, open), (i - delta, close), (i + delta, close), (i + delta, open)) for i, open, close in zip(range(len(opens)), opens, closes) ] downSegments = [((i, low), (i, min(open, close))) for i, low, high, open, close in zip( range(len(lows)), lows, highs, opens, closes)] upSegments = [((i, max(open, close)), (i, high)) for i, low, high, open, close in zip( range(len(lows)), lows, highs, opens, closes)] rangeSegments = upSegments + downSegments 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)] 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) / 2 miny = min([low for low in lows]) maxy = max([high for high in highs]) corners = (minx, miny), (maxx, maxy) ax.update_datalim(corners) # add these last rangeCollection.set_alpha(0.4) barCollection.set_alpha(0.4) ax.collections.clear() ax.add_collection(rangeCollection) ax.add_collection(barCollection) return [rangeCollection, barCollection]
def python_wasserstein(): #%% parameters n = 100 # nb bins # bin positions x = np.arange(n, dtype=np.float64) # Gaussian distributions a1 = ot.datasets.make_1D_gauss(n, m=20, s=5) # m= mean, s= std a2 = ot.datasets.make_1D_gauss(n, m=60, s=8) # creating matrix A containing all distributions A = np.vstack((a1, a2)).T n_distributions = A.shape[1] # loss matrix + normalization M = ot.utils.dist0(n) M /= M.max() #%% barycenter computation alpha = 0.2 # 0<=alpha<=1 weights = np.array([1 - alpha, alpha]) # l2bary bary_l2 = A.dot(weights) # wasserstein reg = 1e-3 bary_wass = ot.bregman.barycenter_sinkhorn(A, M, reg, weights) plt.figure(2) plt.clf() plt.subplot(2, 1, 1) for i in range(n_distributions): plt.plot(x, A[:, i]) plt.title('Distributions') plt.subplot(2, 1, 2) plt.plot(x, bary_l2, 'r', label='l2') plt.plot(x, bary_wass, 'g', label='Wasserstein') plt.legend() plt.title('Barycenters') plt.tight_layout() #%% barycenter interpolation n_alpha = 11 alpha_list = np.linspace(0, 1, n_alpha) B_l2 = np.zeros((n, n_alpha)) B_wass = np.copy(B_l2) for i in range(0, n_alpha): alpha = alpha_list[i] poids = np.array([1 - alpha, alpha]) print(poids) B_l2[:, i] = A.dot(poids) B_wass[:, i] = ot.bregman.barycenter_sinkhorn(A, M, reg, poids) #%% plot interpolation plt.figure(4) cmap = plt.cm.get_cmap('viridis') verts = [] zs = alpha_list for i, z in enumerate(zs): ys = B_wass[:, i] verts.append(list(zip(x, ys))) ax = plt.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) plt.title('Barycenter interpolation with Wasserstein') plt.tight_layout() plt.show()
def waterfall(self, xgrid, ygrid, zarray, colors=None, xlabel="Mass", ylabel = ""): self.xlabel = xlabel if xlabel == "Mass": try: self.kda_test(xgrid[0]) if self.kdnorm==1000: xgrid2 = [] for x in xgrid: x = x/self.kdnorm xgrid2.append(x) xgrid = xgrid2 except: self.kdnorm = 1 self.clear_plot("nopaint") self.subplot1 = self.figure.add_axes(self._axes, projection='3d', proj_type="ortho") verts = [] for i, z in enumerate(zarray): verts.append(list(zip(xgrid[i], ygrid[i]))) # ax = self.figure.gca(projection='3d') if colors is None: colors = cc('r') # wc = cc('w') poly = PolyCollection(verts, edgecolors=colors, facecolors=colors) #poly.set_facecolor((1,1,1,0)) poly.set_alpha(0.7) self.subplot1.add_collection3d(poly, zs=zarray, zdir='y') xgrid = np.hstack(xgrid) ygrid = np.hstack(ygrid) self.subplot1.set_xlabel(self.xlabel) self.subplot1.set_xlim3d(np.amin(xgrid), np.amax(xgrid)) self.subplot1.set_ylabel(ylabel) self.subplot1.set_ylim3d(np.amax(zarray), np.amin(zarray)) #self.subplot1.set_zlabel('Intensity') self.subplot1.set_zlim3d(np.amin(ygrid), np.amax(ygrid)) self.subplot1.get_zaxis().set_ticks([0, np.amax(ygrid) / 2, np.amax(ygrid)]) self.subplot1.get_zaxis().set_ticklabels(["0", '%', "100"]) self.subplot1.xaxis.pane.fill = False self.subplot1.yaxis.pane.fill = False self.subplot1.zaxis.pane.fill = False # Now set color to white (or whatever is "invisible") self.subplot1.xaxis.pane.set_edgecolor('w') self.subplot1.yaxis.pane.set_edgecolor('w') self.subplot1.zaxis.pane.set_edgecolor('w') # Bonus: To get rid of the grid as well: self.subplot1.grid(False) self.canvas = self.figure.canvas for cid in self.cids: self.canvas.mpl_disconnect(cid) self.cids.append(self.canvas.mpl_connect('button_release_event', self.onmove)) try: self.repaint() except MemoryError: print("Memory Error: Not updating 2D plot") self.flag = True
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)
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_mesh, r_mesh: These control how man column and row iso lines will be projected onto the 3d plot. For example, if c_mesh=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_mesh 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', '') labelsize = pltkwargs.pop('labelsize', pvconfig.LABELSIZE) #Can also be ints titlesize = pltkwargs.pop('titlesize', pvconfig.TITLESIZE) # Choose plot kind kind = pltkwargs.pop('kind', 'contour') grid = pltkwargs.pop('grid', True) # 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) outline = pltkwargs.pop('outline', None) if outline: if kind != 'surf' and kind != 'waterfall': raise PlotError( '"outline" is only valid for "surf" and "waterfall"' ' plots. Please use color/cmap for all other color' ' designations.') fig = pltkwargs.pop('fig', None) ax = pltkwargs.pop('ax', None) fill = pltkwargs.pop('fill', pvconfig.FILL_CONTOUR) 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', pvconfig.NUM_CONTOURS) 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 if 'mesh' in pltkwargs: pltkwargs['c_mesh'] = pltkwargs['r_mesh'] = pltkwargs.pop('mesh') # Defaults will be ignored if mesh or ciso in kwargs ciso_default = pvconfig.C_MESH if len(ts.columns) < ciso_default: ciso_default = len(ts.columns) riso_default = pvconfig.R_MESH if len(ts.index) < riso_default: riso_default = len(ts.index) c_mesh = pltkwargs.pop('c_mesh', ciso_default) r_mesh = pltkwargs.pop('r_mesh', riso_default) if c_mesh > ts.shape[1] or c_mesh < 0: raise PlotError( '"c_mesh/column mesh" must be between 0 and %s, got "%s"' % (ts.shape[1], c_mesh)) if r_mesh > ts.shape[0] or r_mesh < 0: raise PlotError( '"r_mesh/row mesh" must be between 0 and %s, got "%s"' % (ts.shape[0], r_mesh)) if c_mesh == 0: cstride = 0 else: cstride = _ir(ts.shape[1] / float(c_mesh)) if r_mesh == 0: rstride = 0 else: rstride = _ir(ts.shape[0] / float(r_mesh)) 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 # PLT.CONTOUR() doesn't take 'color'; rather, takes 'colors' for now if 'color' in pltkwargs: if kind == 'contour' or kind == 'contour3d': 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': # Cornercase datetimeindex and offest from add projection hack try: pltkwargs['offset'] = dates.date2num(pltkwargs['offset']) except Exception: pass if fill: #Values of DTI doesn't work mappable = ax.contourf(xx, yy, ts.values, contours, **pltkwargs) #linewidths is a pltkwargs arg else: mappable = ax.contour(xx, yy, ts.values, 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) if outline: try: pltkwargs['cmap'] = pu.cmget(outline) except Exception: #Don't change; attribute error fails when outline=None pltkwargs['color'] = outline pltkwargs.pop('cmap') custom_wireframe(ax, xx, yy, ts, **pltkwargs) # Wires are thrown out, since mappable is the surface, and only mappable returned elif kind == 'wire': pltkwargs.setdefault('color', 'black') mappable = custom_wireframe(ax, xx, yy, ts, **pltkwargs) elif kind == 'waterfall': # Parse outline color (if colormap, error!) try: pu.cmget(outline) except Exception: pltkwargs['edgecolors'] = outline else: raise PlotError( 'Waterfall "outline" must be a solid color, not colormap.') 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 (waterfall doesn't have strides: not a surface!) 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: cb = fig.colorbar(mappable, ax=ax) # Label colorbar on contour since no 3d-zlabel if kind == 'contour': cb.set_label(zlabel) except Exception: raise PlotError("Colorbar failed; did you pass a colormap?") if grid: if grid == True: ax.grid() else: ax.grid(color=grid) #Let's any supported color in # 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)
x_042_peak_eV,y_042_peak=np.loadtxt('data/Y24901L.txt', unpack=True, usecols = [0,1])#peak at 4.2 x_062_peak_eV,y_062_peak=np.loadtxt('data/Y24902L.txt', unpack=True, usecols = [0,1])#peak at 6.2 x_082_peak_eV,y_082_peak=np.loadtxt('data/Y24903L.txt', unpack=True, usecols = [0,1])#peak at 8.2 x_102_peak_eV,y_102_peak=np.loadtxt('data/Y24904L.txt', unpack=True, usecols= [0,1])#peak at 10.2 x_132_peak_eV,y_132_peak=np.loadtxt('data/Y24905L.txt', unpack=True, usecols= [0,1])#peak at 13.2 x_182_peak_eV,y_182_peak=np.loadtxt('data/Y24906L.txt', unpack=True, usecols= [0,1])#peak at 18.2 x_ex0 = x#np.arange(0, 10, 0.4) y_ex0 = y#,y_042_peak,y_062_peak,y_082_peak,y_102_peak,y_132_peak,y_182_peak] z_ex0 = 0#[0.0, 4.2, 6.2, 8.2, 10.2, 13.2, 18.2] vert_ex0 = [] #for z in zs: #ys[0], ys[-1] = 0, 0 vert_ex0.append(list(zip(x_ex0, y_ex0))) poly_ex0 = PolyCollection(vert_ex0, facecolors = cc('#FFFFFF'))#, cc('c'), cc('r'), cc('g'), cc('y'), cc('m'), cc('k')]) poly_ex0.set_alpha(0.9) ax.add_collection3d(poly_ex0, zs=z_ex0, zdir='y') x_0 = x_nopeak_eV#np.arange(0, 10, 0.4) y_0 = y_nopeak#,y_042_peak,y_062_peak,y_082_peak,y_102_peak,y_132_peak,y_182_peak] z_0 = 10.0#[0.0, 4.2, 6.2, 8.2, 10.2, 13.2, 18.2] vert_0 = [] #for z in zs: #ys[0], ys[-1] = 0, 0 vert_0.append(list(zip(x_0, y_0))) poly_0 = PolyCollection(vert_0, facecolors = cc('#FFDD00'))#, cc('c'), cc('r'), cc('g'), cc('y'), cc('m'), cc('k')]) poly_0.set_alpha(0.9) ax.add_collection3d(poly_0, zs=z_0, zdir='y') x_1 = x_nopeak_eV#np.arange(0, 10, 0.4) y_1 = y_042_peak#,y_042_peak,y_062_peak,y_082_peak,y_102_peak,y_132_peak,y_182_peak]
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)
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()
colors = plt.get_cmap('tab10').colors for ii in np.arange(n_test): ll = ii % (n_columns * n_rows) ax = plt.subplot(gs[ll]) plt.plot(t, test_data[ii], color = (0, 0, 0)) if test_label_s[ii] == 1: verts = np.zeros((1, 4, 2)) ts = np.array([t[0], t[-1], t[-1], t[0]]) ys = np.array([dmin, dmin, dmax, dmax]) verts[0] = list(zip(ts, ys)) poly = PolyCollection(verts, facecolors = colors[0], \ edgecolors = None) poly.set_alpha(0.2) ax.add_collection(poly) ax.set_ylim([dmin, dmax]) if ii % (n_columns * n_rows) == (n_columns * n_rows - 1): gs.tight_layout(fig) gs.update(wspace = 0.1, hspace = 0.1) pdf.savefig() plt.close() fig = plt.figure(figsize = (20, 25)) gs = gridspec.GridSpec(n_columns, n_rows) gs.tight_layout(fig)
def plot_geocol_mpl(gc, color=None, facecolor='0.3', edgecolor='0.7', alpha=1., linewidth=0.2, marker='o', marker_size=20, ax=None, figsize=(9, 9)): ''' Plot geographical data from the `geometry` column of a PySAL geotable to a matplotlib backend. ... Parameters ---------- gc : DataFrame GeoCol with data to be plotted. color : str/tuple/Series [Optional. Default=None] Wrapper that sets both `facecolor` and `edgecolor` at the same time. If set, `facecolor` and `edgecolor` are ignored. It allows for either a single color or a Series of the same length as `gc` with colors, indexed on `gc.index`. facecolor : str/tuple/Series [Optional. Default='0.3'] Color for polygons and points. It allows for either a single color or a Series of the same length as `gc` with colors, indexed on `gc.index`. edgecolor : str/tuple/Series [Optional. Default='0.7'] Color for the polygon and point edges. It allows for either a single color or a Series of the same length as `gc` with colors, indexed on `gc.index`. alpha : float/Series [Optional. Default=1.] Transparency. It allows for either a single value or a Series of the same length as `gc` with colors, indexed on `gc.index`. linewidth : float/Series [Optional. Default=0.2] Width(s) of the lines in polygon and line plotting (not applicable to points). It allows for either a single value or a Series of the same length as `gc` with colors, indexed on `gc.index`. marker : 'o' marker_size : int ax : AxesSubplot [Optional. Default=None] Pre-existing axes to which append the collections and setup figsize : tuple w,h of figure ''' geom = type(gc.iloc[0]) if color is not None: facecolor = edgecolor = color draw = False if not ax: f, ax = plt.subplots(1, figsize=figsize) draw = True # Geometry plotting patches = [] ids = [] # Polygons if geom == ps.cg.shapes.Polygon: for id, shape in gc.items(): for ring in shape.parts: xy = np.array(ring) patches.append(xy) ids.append(id) mpl_col = PolyCollection(patches) # Lines elif geom == ps.cg.shapes.Chain: for id, shape in gc.items(): for xy in shape.parts: patches.append(xy) ids.append(id) mpl_col = LineCollection(patches) facecolor = 'None' # Points elif geom == ps.cg.shapes.Point: edgecolor = facecolor xys = np.array(list(zip(*gc))).T ax.scatter(xys[:, 0], xys[:, 1], marker=marker, s=marker_size, c=facecolor, edgecolors=edgecolor, linewidths=linewidth) mpl_col = None # Styling mpl collection (polygons & lines) if mpl_col: if type(facecolor) is pd.Series: facecolor = facecolor.reindex(ids) mpl_col.set_facecolor(facecolor) if type(edgecolor) is pd.Series: edgecolor = edgecolor.reindex(ids) mpl_col.set_edgecolor(edgecolor) if type(linewidth) is pd.Series: linewidth = linewidth.reindex(ids) mpl_col.set_linewidth(linewidth) if type(alpha) is pd.Series: alpha = alpha.reindex(ids) mpl_col.set_alpha(alpha) ax.add_collection(mpl_col, autolim=True) ax.autoscale_view() ax.set_axis_off() if draw: plt.axis('equal') plt.show() return None
depth += delDepth 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
ax = fig.gca(projection='3d') a, b = -3, 3 gs = 100 xs = np.linspace(a, b, gs) # == Build verts == # greys = np.linspace(0.3, 0.7, nmax) verts = [] for n in ns: density = gaussian_kde(Y[:,n-1]) ys = density(xs) verts.append(zip(xs, ys)) poly = PolyCollection(verts, facecolors = [str(g) for g in greys]) poly.set_alpha(0.85) ax.add_collection3d(poly, zs=ns, zdir='x') #ax.text(np.mean(rhos), a-1.4, -0.02, r'$\beta$', fontsize=16) #ax.text(np.max(rhos)+0.016, (a+b)/2, -0.02, r'$\log(y)$', fontsize=16) ax.set_xlim3d(1, nmax) ax.set_xticks(ns) ax.set_xlabel("n") ax.set_yticks((-3, 0, 3)) ax.set_ylim3d(a, b) ax.set_zlim3d(0, 0.4) ax.set_zticks((0.2, 0.4)) plt.show()
def double_integral(func, limits, res=1000, plot=True): s = 0 a, b = limits[0], limits[1] ys = np.linspace(a, b, res) c_is_func = callable(limits[2]) d_is_func = callable(limits[3]) y_list = np.linspace(limits[0], limits[1], res) for y in ys: if c_is_func: c = limits[2](y) else: c = limits[2] if d_is_func: d = limits[3](y) else: d = limits[3] dA = ((b - a) / res) * ((d - c) / res) xs = np.linspace(c, d, res) s += np.sum(func(xs, y)) * dA if plot: res = res // 20 y_list = np.linspace(limits[0], limits[1], res) if c_is_func: x_min = limits[2](y_list) else: x_min = limits[2] * np.ones(len(y_list)) if d_is_func: x_max = limits[3](y_list) else: x_max = np.ones(len(y_list)) * limits[3] fig = plt.figure() ax = Axes3D(fig) a = np.linspace(x_min[0], x_max[0], res) b = np.linspace(x_max[-1], x_min[-1], res) c = x_min[::-1] d = x_max pts_x = np.append(a, d) pts_x = np.append(pts_x, b) pts_x = np.append(pts_x, c) pts_y = np.append(y_list[0] * np.ones(res), y_list) pts_y = np.append(pts_y, y_list[-1] * np.ones(res)) pts_y = np.append(pts_y, y_list[::-1]) verts = [(list(zip(pts_x, pts_y)))] poly = PolyCollection(verts, facecolor="b") poly.set_alpha(1) ax.add_collection3d(poly) ax.plot(pts_x, pts_y, color="b") print(min(x_min)) x = np.linspace(min(x_min), max(x_max), res) y = np.linspace(max(y_list), min(y_list), res) x, y = np.meshgrid(x, y) z = func(x, y) surf = ax.plot_surface(x, y, z, cmap="viridis") ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") plt.show() return s
def plot_y_precentiles(self, y_percentiles_smoothed_list, fov_list, thresholds): fig = plt.figure() ### Subplot dimensions of plot root_list_len = np.ceil(np.sqrt(len(y_percentiles_smoothed_list))) ### Looping through each fov idx = 0 for j, y_percentiles_smoothed in enumerate( y_percentiles_smoothed_list): ### Managing Subplots idx += 1 ax = fig.add_subplot(root_list_len, root_list_len, idx, projection='3d') ### Making list of vertices (tuples) for use with PolyCollection vert_arr = np.array([ np.add.accumulate(np.ones(y_percentiles_smoothed.shape, dtype=int), axis=0), y_percentiles_smoothed ]) verts = [] for t in range(vert_arr.shape[2]): w_vert = vert_arr[:, :, t] verts.append([(w_vert[0, i], w_vert[1, i]) for i in range(0, w_vert.shape[1], 10)]) ### Making counting array for y position zs = np.add.accumulate(np.ones(len(verts))) ### Creating PolyCollection and add to plot poly = PolyCollection(verts, facecolors=['b']) poly.set_alpha(0.5) ax.add_collection3d(poly, zs=zs, zdir='y') ### Depecting thresholds as straight lines x_len = y_percentiles_smoothed.shape[0] y_len = y_percentiles_smoothed.shape[1] thr_x = np.repeat(np.add.accumulate(np.ones( x_len, dtype=int))[:, np.newaxis], y_len, axis=1).T.flatten() thr_y = np.repeat(np.add.accumulate(np.ones(y_len, dtype=int)), x_len) # thr_z = np.concatenate( [np.repeat(threshold, x_len) for threshold in thresholds[j]], axis=0) for i in range(0, x_len * y_len, x_len): ax.plot(thr_x[i:i + x_len], thr_y[i:i + x_len], thr_z[i:i + x_len], c='r') ### Plot lebels ax.set_title("FOV: " + str(fov_list[j])) ax.set_xlabel('y position') ax.set_xlim3d(0, vert_arr[0, -1, 0]) ax.set_ylabel('time (s)') ax.set_ylim3d(0, len(verts)) ax.set_zlabel('intensity') ax.set_zlim3d(0, np.max(vert_arr[1])) plt.show()
zdir='y', zorder=-1, color='C0', alpha=1.0 - norm(np.abs(time[i] - time[time_idx]))) # def EnvelopeFunction(t,amp,width,power,offset): # return amp*np.exp(-np.power((t-offset)/width,power)) # popt, pcov = curve_fit(EnvelopeFunction, time, max_field, p0=(1.0,1.0,1.0,0.0)) poly = PolyCollection(verts, rasterized=True, facecolor=None, edgecolor='k', lw=0.7) poly.set_alpha(0.5) #ax.scatter(time, max_field, zs=x_cut_time[0,0], zdir='x', zorder=-1) #ax.plot(time, EnvelopeFunction(time,*popt), zs=x_cut_time[0,0], zdir='x', zorder=-1) #ax.plot(x_cut_time[:,time_idx], field_xcut_time[:,time_idx], zs=time[-1], zdir='y', zorder=-1) ax.add_collection3d(poly, zs=time, zdir='y') ax.ticklabel_format(style='sci', axis='z', scilimits=(0, 0)) ax.set_xlim3d(x_cut_time.min(), x_cut_time.max()) ax.set_xlabel(r'$x$ [$\mu m$]') ax.set_ylim3d(np.amin(time), np.amax(time)) ax.set_ylabel('Time (fs)') ax.invert_yaxis() ax.invert_xaxis() ax.set_zlim3d(0.0, field_xcut_time.max()) ax.set_zlabel('Amplitude', rotation=90) plt.savefig(folderName + "/ElectricIntensityTimeWaterfall.pdf", dpi=500) plt.close()
def waterfall_plot(x, y, z, x_label="", y_label="", z_label="", use_poly=True, alpha=0.2, filename="", y_range=None, x_range=None): """ :param Dvector x: First axis :param Dvector y: Second axis :param Dvector z: Third axis :param string x_label: Label for first axis :param string y_label: Label for second axis :param string z_label: Label for third axis :param bool use_poly: Whether to use filled polygons :param double alpha: Set transparency of filled polygons :param string filename: Location to save file. If "", use interactive plot :param Dvector y_range: Change range of second axis if not None :param Dvector x_range: Change range of first axis if not None Generate a waterfall plot. """ print("\nGenerating waterfall_plot...") plt.clf() fig = plt.figure() ax = fig.gca(projection='3d') data = [list(zip(x, y[n])) for n, z_n in enumerate(z)] if use_poly: from matplotlib.collections import PolyCollection # Parameter closed MUST be set False if axis does not start at zero: curves = PolyCollection(data, closed=False) else: from matplotlib.collections import LineCollection curves = LineCollection(data) curves.set_alpha(alpha) ax.add_collection3d(curves, zs=z, zdir='y') ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.set_zlabel(z_label) if x_range is None: ax.set_xlim3d(x[0], x[-1]) else: ax.set_xlim3d(x_range) # Note the use of z as a parameter for ylim and also the reverse: ax.set_ylim3d(z[0], z[-1]) if y_range is not None: ax.set_zlim3d(y_range) # Avoid overlapping axis text: plt.tight_layout() if filename: plt.savefig(filename) print("Wrote file", filename) else: plt.show()
plt.rc('text', usetex=True) plt.rc('font', family='serif') plt.rc('xtick', labelsize=12) plt.rc('ytick', labelsize=12) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for i in range(0, 10): ax.plot(X[i], Y[i], Z[i], color=blue, ls='--', linewidth=2.0) for i in range(0, 6): zs.append(Y[:, i][0]) points = [] points.append((X[:, i][0], 1.0)) points = points + list(zip(X[:, i], Z[:, i])) points.append((X[:, i][-1], 1.0)) verts.append(points) ax.plot(X[:, i], Y[:, i], Z[:, i], color=orage, ls='-', linewidth=2.0) poly = PolyCollection(verts, facecolors=light_orange, linewidths=0) poly.set_alpha(0.3) ax.add_collection3d(poly, zs=zs, zdir='y') ax.set_xlabel('Cluster Size', fontsize=16) ax.set_ylabel('Size Per Node (GB)', fontsize=16) ax.set_zlabel('Sampling Time (s)', fontsize=16) plt.show()
cc('r'), cc('y'), cc('g'), cc('b'), cc('m'), cc('c'), cc('k'), cc('w') ] if len(ratios) < 8: fc = colors[:len(ratios)] else: fc = colors for c in range(len(ratios) - 8): r = random.random() g = random.random() b = random.random() fc.append((r, g, b)) poly = PolyCollection(verts, facecolors=fc) poly.set_alpha(0.7) #transparency ax.add_collection3d(poly, zs=ratios, zdir='y') ax.set_xlabel('Position') ax.set_xlim3d(min(xs), max(xs)) ax.set_ylabel('E Field Ratio') ax.set_ylim3d(0, max(ratios)) ax.set_zlabel('Change in Intensity') ax.set_zlim3d(miny, maxy) plt.show()
def volume_overlay(self, ax, opens, closes, volumes, colorup='g', 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 """ colorup = mcolors.to_rgba(colorup, alpha) colordown = mcolors.to_rgba(colordown, 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, ), ) barCollection.set_alpha(0.4) corners = (0, 0), (len(bars), max(volumes)) ax.collections.clear() ax.add_collection(barCollection) ax.update_datalim(corners) #ax.autoscale(True) #ax.set_aspect('auto') #ax.autoscale(False) # add these last return [barCollection]
global depth # 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') # Points
(linewidth[AC_i]**2 + detuning_range**2)) freq_list_GHz = np.real(sim_AC.Eig_values[AC_i] + detuning_range) * 1e-9 interp_spectrum = np.interp(interp_grid, freq_list_GHz, gain_list) interp_values += interp_spectrum freqs_gains.append(list(zip(interp_grid, abs(interp_values)))) print('Widths', waveguide_widths) print('n_effs', n_effs) # Plot a 'waterfall' plot. print('Plotting waterfall') fig = plt.figure() ax = fig.gca(projection='3d') poly = PolyCollection(freqs_gains) poly.set_alpha(0.7) ax.add_collection3d(poly, zs=waveguide_widths, zdir='y') ax.set_xlabel('Frequency (GHz)', fontsize=14) ax.set_xlim3d(int_min, int_max) ax.set_ylabel('Width (nm)', fontsize=14) ax.set_ylim3d(waveguide_widths[0], waveguide_widths[-1]) ax.set_zlabel('|Gain| (1/Wm)', fontsize=14) ax.set_zlim3d(0, 1500) # We change the fontsize of minor ticks label plt.tick_params(axis='both', which='major', labelsize=12, pad=-2) plt.savefig(prefix_str + 'gain_spectra-waterfall.pdf') plt.savefig(prefix_str + 'gain_spectra-waterfall.png') plt.close() end = time.time() print("\n Simulation time (sec.)", (end - start))
for z in range(len(ratios)): xs = list(shg[1:,0]) ys = list(shg[1:,z+1]) verts.append([(max(xs),0)]+list(zip(xs, ys))+[(min(xs),0)]) if max(ys) > maxy: maxy = max(ys) if min(ys) < miny: miny = min(ys) colors = [cc('r'), cc('y'), cc('g'), cc('b'), cc('m'), cc('c'), cc('k'), cc('w')] if len(ratios)<8: fc = colors[:len(ratios)] else: fc = colors for c in range(len(ratios)-8): r = random.random() g = random.random() b = random.random() fc.append((r,g,b )) poly = PolyCollection(verts, facecolors=fc) poly.set_alpha(0.7) #transparency ax.add_collection3d(poly, zs=ratios, zdir='y') ax.set_xlabel('Position') ax.set_xlim3d(min(xs), max(xs)) ax.set_ylabel('E Field Ratio') ax.set_ylim3d(0, max(ratios)) ax.set_zlabel('Change in Intensity') ax.set_zlim3d(miny,maxy) plt.show()
#### 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')
from mpl_toolkits.mplot3d import Axes3D 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')
verts = [] zs = [0.1, 0.2, 0.3] verts.append(list(zip(times, reduces))) verts.append(list(zip(times, maps))) verts.append(list(zip(times, shuffles))) poly = PolyCollection(verts, offsets=None, facecolors=[cc('#48d1cc'), cc('r'), cc('#f0ffff')], closed=False) poly.set_alpha(0.75) ax.add_collection3d(poly, zs=zs, zdir='y') ax.invert_zaxis() ax.view_init(elev=15., azim=280) ax.set_xlabel('Time (s)') ax.set_xlim3d(0, last_time) ax.set_ylim3d(0.1, 0.3) ax.set_zlabel('\# Tasks') ax.set_zlim3d(0, 12) ax.axes.get_yaxis().set_visible(False) ax.axes.get_yaxis().set_ticks([])
def plot_spec_poly(series, moments=None, fcut=1.e-20, is_info=False): # moments = moments or (1., 3., 5, 10., 15., 25., 35., 50., 70., 100., 120., 150., 200.) # moments = moments or np.arange(0., 200., 3) moments = moments or np.exp(np.linspace(np.log(0.5), np.log(400.), 40)) # init graph fig = plt.figure() ax = fig.gca(projection='3d') pos = 0 t_data = [] for i, t in enumerate(series.Time): if t > moments[pos]: t_data.append(t) pos += 1 verts = [] T_cols = [] x_lim = [float("inf"), float("-inf")] z_lim = [float("inf"), float("-inf")] for i, t in enumerate(t_data): spec = series.get_spec_by_time(t_data[i]) spec.cut_flux(fcut * max(spec.Flux)) # cut flux ys = spec.Flux # ys = np.log10(ys) wl = spec.Wl * ps.phys.cm_to_angs verts.append(list(zip(wl, ys))) x_lim[0] = min(x_lim[0], np.min(wl)) x_lim[1] = max(x_lim[1], np.max(wl)) z_lim[0] = min(z_lim[0], np.min(ys)) z_lim[1] = max(z_lim[1], np.max(ys)) T_cols.append(spec.T_color) if is_info: print("time: %f T_color=%f" % (t, spec.T_color)) # print "time: %f T_wien=%f wl_max=%f" % (t_data[i], spec.temp_wien, spec.wl_flux_max) Tmap = np.log(T_cols / np.min(T_cols)) color_map = color_map_temp() m = plt.cm.ScalarMappable(cmap=color_map) m.set_array(Tmap) facecolors = m.to_rgba(Tmap * 1.e-4) poly = PolyCollection(verts, facecolors=facecolors, linewidths=1.5) # np.ones(len(t_data))) poly.set_alpha(0.5) ax.add_collection3d(poly, zs=t_data, zdir='y') # Create a color bar with 11 ticks cbar = plt.colorbar(m, shrink=0.85) ticks = np.linspace(min(Tmap), max(Tmap), 10) ticks_lbl = np.round(np.exp(ticks) * np.min(T_cols), -2) cbar.ax.set_yticklabels(ticks_lbl) cbar.ax.yaxis.set_label_text("Color temperature [K]") ax.set_xlim3d(x_lim) ax.set_ylim3d(min(t_data), max(t_data)) ax.set_zlim3d(z_lim) # ax.set_xscale('log') ax.set_zscale('log') ax.xaxis.set_label_text('Wavelength [A]') ax.yaxis.set_label_text('Time [days]') ax.zaxis.set_label_text('Flux [a.u.]') return fig
def test5(): numpy.random.seed(42) data = numpy.zeros((5000, 2)) idx = numpy.random.choice(data.shape[0], int(data.shape[0] / 2), replace=False) data[idx, 1] = 1 idx0 = data[:, 1] == 0 idx1 = data[:, 1] == 1 data[idx0, 0] = numpy.random.normal(100, 30, numpy.sum(idx0)) data[idx1, 0] = numpy.random.normal(200, 30, numpy.sum(idx1)) print(data) featureNames = ["Gaussian", "Categorical"] featureTypes = ["continuous", "discrete"] # spn = SPN.LearnStructure(data, featureTypes=featureTypes, featureNames=featureNames, row_split_method=Splitting.KmeansRows(), col_split_method=Splitting.IndependenceTest(alpha=0.01), # spn = SPN.LearnStructure(data, featureTypes=featureTypes, # featureNames=featureNames, row_split_method=Splitting.KmeansRows(), # col_split_method=Splitting.RDCTest(), spn = SPN.LearnStructure(data, featureTypes=featureTypes, featureNames=featureNames, row_split_method=Splitting.KmeansRows(), col_split_method=Splitting.RDCTestOHEpy(), min_instances_slice=500, cluster_first=True) spn.root.validate() from mpl_toolkits.mplot3d import Axes3D from matplotlib.collections import PolyCollection from matplotlib.colors import colorConverter import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.gca(projection='3d') cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6) xs = np.arange(0, 300, 0.5) verts = [] zs = [0, 1] maxys = 0 for z in zs: testdata = numpy.zeros((len(xs), len(zs))) testdata[:, 0] = xs testdata[:, 1] = z ys = numpy.zeros_like(xs) ys[:] = numpy.exp(spn.root.eval(testdata)) maxys = max(maxys, numpy.max(ys)) ys[0], ys[-1] = 0, 0 verts.append(list(zip(xs, ys))) poly = PolyCollection(verts, facecolors=[cc('r'), cc('g')]) poly.set_alpha(0.7) ax.add_collection3d(poly, zs=zs, zdir='y') ax.set_xlabel('X') ax.set_xlim3d(0, 300) ax.set_ylabel('Y') ax.set_ylim3d(-1, 1) ax.set_zlabel('Z') ax.set_zlim3d(0, maxys) plt.show() ll = spn.root.eval(data) print("Sum LL", numpy.sum(ll))
def tripcolor(ax, *args, **kwargs): """ Create a pseudocolor plot of an unstructured triangular grid to the :class:`~matplotlib.axes.Axes`. The triangulation can be specified in one of two ways; either:: tripcolor(triangulation, ...) where triangulation is a :class:`~matplotlib.tri.Triangulation` object, or :: tripcolor(x, y, ...) tripcolor(x, y, triangles, ...) tripcolor(x, y, triangles=triangles, ...) tripcolor(x, y, mask=mask, ...) tripcolor(x, y, triangles, mask=mask, ...) in which case a Triangulation object will be created. See :class:`~matplotlib.tri.Triangulation` for a explanation of these possibilities. The next argument must be *C*, the array of color values, one per point in the triangulation. The colors used for each triangle are from the mean C of the triangle's three points. The remaining kwargs are the same as for :meth:`~matplotlib.axes.Axes.pcolor`. **Example:** .. plot:: mpl_examples/pylab_examples/tripcolor_demo.py """ if not ax._hold: ax.cla() alpha = kwargs.pop('alpha', 1.0) norm = kwargs.pop('norm', None) cmap = kwargs.pop('cmap', None) vmin = kwargs.pop('vmin', None) vmax = kwargs.pop('vmax', None) shading = kwargs.pop('shading', 'flat') tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, **kwargs) x = tri.x y = tri.y triangles = tri.get_masked_triangles() # Vertices of triangles. verts = np.concatenate((x[triangles][...,np.newaxis], y[triangles][...,np.newaxis]), axis=2) C = np.asarray(args[0]) if C.shape != x.shape: raise ValueError('C array must have same length as triangulation x and' ' y arrays') # Color values, one per triangle, mean of the 3 vertex color values. C = C[triangles].mean(axis=1) if shading == 'faceted': edgecolors = (0,0,0,1), linewidths = (0.25,) else: edgecolors = 'face' linewidths = (1.0,) kwargs.setdefault('edgecolors', edgecolors) kwargs.setdefault('antialiaseds', (0,)) kwargs.setdefault('linewidths', linewidths) collection = PolyCollection(verts, **kwargs) collection.set_alpha(alpha) collection.set_array(C) if norm is not None: assert(isinstance(norm, Normalize)) collection.set_cmap(cmap) collection.set_norm(norm) if vmin is not None or vmax is not None: collection.set_clim(vmin, vmax) else: collection.autoscale_None() ax.grid(False) minx = tri.x.min() maxx = tri.x.max() miny = tri.y.min() maxy = tri.y.max() corners = (minx, miny), (maxx, maxy) ax.update_datalim( corners) ax.autoscale_view() ax.add_collection(collection) return collection
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
# code required to create a 3d, filled line graph fig = plt.figure() ax = fig.gca(projection="3d") cc = lambda arg: colorConverter.to_rgba(arg) verts = [] zs = [0.1, 0.2, 0.3] verts.append(list(zip(times, maps))) verts.append(list(zip(times, shuffles))) verts.append(list(zip(times, reduces))) poly = PolyCollection(verts, offsets=None, facecolors=[cc("r"), cc("#f0ffff"), cc("#48d1cc")], closed=False) poly.set_alpha(0.75) ax.add_collection3d(poly, zs=zs, zdir="y") ax.invert_zaxis() ax.view_init(elev=15.0, azim=280) ax.set_xlabel("Time (s)") ax.set_xlim3d(0, last_time) ax.set_ylim3d(0.1, 0.3) ax.set_zlabel("\# Tasks") ax.set_zlim3d(0, 12) ax.axes.get_yaxis().set_visible(False) ax.axes.get_yaxis().set_ticks([])
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
def plot_seed(self) -> SimPhase: ''' Visualize the cell cluster seed by a prior call to the :meth:`seed` method and export the resulting plots and animations to various output files, specified by the current configuration file. Returns ---------- SimPhase High-level simulation phase instance encapsulating all objects internally created by this method to run this phase. ''' # Log this plotting attempt. logs.log_info( 'Plotting cell cluster with configuration file "%s".', self._p.conf_basename) # If an initialization does *NOT* already exist, raise an exception. _die_unless_file_pickled( filename=self._p.seed_pickle_filename, subcommand='seed', subcommand_label='Seed') # Load the seed from cache. cells, _ = fh.loadWorld(self._p.seed_pickle_filename) logs.log_info('Cell cluster loaded.') # Simulation phase, created *AFTER* unpickling these objects above phase = SimPhase( kind=SimPhaseKind.SEED, p=self._p, cells=cells, callbacks=self._callbacks, ) # Initialize core simulation data structures. phase.sim.init_core(phase) phase.dyna.init_profiles(phase) #FIXME: Refactor into a seed-specific plot pipeline. Dreaming androids! if self._p.autosave: savedImg = pathnames.join(self._p.init_export_dirname, 'fig_') # if self._p.plot_cell_cluster: # fig_tiss, ax_tiss, cb_tiss = viz.clusterPlot( # self._p, phase.dyna, cells, clrmap=self._p.background_cm) if self._p.autosave: savename10 = savedImg + 'cluster_mosaic' + '.png' plt.savefig(savename10, format='png', transparent=True) if self._p.plot.is_after_sim_show: plt.show(block=False) if self._p.is_ecm: # and self._p.plot_cluster_mask: plt.figure() ax99 = plt.subplot(111) plt.imshow( np.log10(phase.sim.D_env_weight.reshape(phase.cells.X.shape)), origin='lower', extent=[ self._p.um * phase.cells.xmin, self._p.um * phase.cells.xmax, self._p.um * phase.cells.ymin, self._p.um * phase.cells.ymax, ], cmap=self._p.background_cm, ) plt.colorbar() cell_edges_flat = self._p.um * phase.cells.mem_edges_flat coll = LineCollection(cell_edges_flat, colors='k') coll.set_alpha(1.0) ax99.add_collection(coll) plt.title('Logarithm of Environmental Diffusion Weight Matrix') if self._p.autosave: savename10 = savedImg + 'env_diffusion_weights' + '.png' plt.savefig(savename10, format='png', transparent=True) if self._p.plot.is_after_sim_show: plt.show(block=False) plt.figure() plt.imshow( cells.maskM, origin='lower', extent=[ self._p.um * phase.cells.xmin, self._p.um * phase.cells.xmax, self._p.um * phase.cells.ymin, self._p.um * phase.cells.ymax, ], cmap=self._p.background_cm, ) plt.colorbar() plt.title('Cluster Masking Matrix') if self._p.autosave: savename = savedImg + 'cluster_mask' + '.png' plt.savefig(savename, format='png', transparent=True) if self._p.plot.is_after_sim_show: plt.show(block=False) # Plot gap junctions. # if self._p.plot_cell_connectivity: plt.figure() ax_x = plt.subplot(111) if self._p.showCells: base_points = np.multiply(phase.cells.cell_verts, self._p.um) col_cells = PolyCollection( base_points, facecolors='k', edgecolors='none') col_cells.set_alpha(0.3) ax_x.add_collection(col_cells) con_segs = phase.cells.nn_edges connects = self._p.um * np.asarray(con_segs) collection = LineCollection(connects, linewidths=1.0, color='b') ax_x.add_collection(collection) plt.axis('equal') plt.axis([ self._p.um * phase.cells.xmin, self._p.um * phase.cells.xmax, self._p.um * phase.cells.ymin, self._p.um * phase.cells.ymax, ]) ax_x.set_xlabel('Spatial x [um]') ax_x.set_ylabel('Spatial y [um') ax_x.set_title('Cell Connectivity Network') if self._p.autosave: savename10 = savedImg + 'gj_connectivity_network' + '.png' plt.savefig(savename10, format='png', transparent=True) if self._p.turn_all_plots_off is False: plt.show(block=False) else: logs.log_info( 'Plots exported to init results folder ' 'defined in configuration file "%s".', self._p.conf_basename) # Return this phase. return phase
print(fname) radius = re.search( 'R(\d+(\.\d+)?)', os.path.basename(fname)).groups()[0] # print(float(re.findall('_R\d\d_', fname)[0].replace('_','').replace('R',''))) # zs.append(float(re.findall('_R\d\d_', fname)[0].replace('_','').replace('R',''))) print(radius) zs.append(radius) except IndexError: zs.append(counter) print(zs) counter += 1 verts.append(list(zip(spctr.x, spctr.y))) cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.3) poly = PolyCollection(verts, facecolors=[cc('r'), cc('g'), cc('b'), cc('y')]) poly.set_alpha(0.7) fig = plt.figure() ax = fig.gca(projection='3d') ax.add_collection3d(poly, zs=zs, zdir='y') ax.set_xlabel('Energy, eV') # ax.set_xlim3d(0, 10) ax.set_ylabel('Signal') # ax.set_ylim3d(-1, 4) ax.set_zlabel('Radius, nm') # ax.set_zlim3d(0, 1) plt.show()
def animate_convolution(x, h, y, t, tau, td, taud, interval=75): """Plot animation of graphical representation of linear convolution. Parameters ---------- x : sympy function First function to be convolved. h: sympy function Second function to be convolved. t: sympy variable Independent variable for functions (e.g. time). tau: sympy variable Integration variable for convolution. td: array like Discrete values of independent variable evaluated for plot. taud: Discrete values of integration variable evaluated for animation. interval: Interval in ms between frames of animation. Returns ------- matplotlib.animation.FuncAnimation object. """ def animate(ti): p = sym.plot(x.subs(t, tau), (tau, taud[0], taud[-1]), show=False) line_x.set_segments(p[0].get_segments()) p = sym.plot(h.subs(t, t - tau).subs(t, ti), (tau, taud[0], taud[-1]), show=False) line_h.set_segments(p[0].get_segments()) p = sym.plot(y, (t, taud[0], taud[-1]), show=False) line_y.set_segments(p[0].get_segments()) p = sym.plot(x.subs(t, tau) * h.subs(t, ti - tau), (tau, -5, 5), show=False) points = p[0].get_points() verts = [[(xi[0], xi[1]) for xi in np.transpose(np.array(points))]] fill.set_verts(verts) dot.set_data(ti, y.subs(t, ti)) # define line/fill collections and setup plot fig, ax = plt.subplots(2, 1) fig.subplots_adjust(hspace=0.5) plt.close() # suppresses empty plot in notebook fill = PolyCollection([], facecolors='r') fill.set_alpha(0.3) ax[0].add_collection(fill) line_x = LineCollection([], colors='C0') line_x.set_label(r'$x(\tau)$') ax[0].add_collection(line_x) line_h = LineCollection([], colors='C1') line_h.set_label(r'$h(t - \tau)$') ax[0].add_collection(line_h) line_y = LineCollection([], colors='C2') line_y.set_label(r'$y(t)$') ax[1].add_collection(line_y) dot, = ax[1].plot([], 'ro') for axi in ax: axi.spines['left'].set_position('zero') axi.spines['bottom'].set_position('zero') axi.spines['right'].set_color('none') axi.spines['top'].set_color('none') axi.xaxis.set_ticks_position('bottom') axi.yaxis.set_ticks_position('left') axi.set_xlim((-3, 4)) axi.set_ylim((-.1, 1.2)) ax[0].set_xlabel(r'$\tau$', horizontalalignment='right', x=1.0) ax[0].legend(loc='upper right') ax[1].set_xlabel(r'$t$', horizontalalignment='right', x=1.0) ax[1].legend(loc='upper right') return FuncAnimation(fig, animate, td, interval=interval)