def preparePlot(self): """Prepare the plotting window""" plt.hot() self.figure=plt.figure(self.figNr) self.figure.clear() # this is black magic that makes the legend work with two axes if self.hasSubplotHost: self.axis1=SubplotHost(self.figure,111) self.figure.add_subplot(self.axis1) else: self.axis1=self.figure.add_subplot(111) self.axis1.set_xlabel(self.xlabel) self.axis1.set_ylabel(self.ylabel) if len(self.alternate)>0: self.axis2=self.axis1.twinx() self.axis2.set_ylabel(self.ylabel2) try: if self.spec.logscale: self.axis1.set_yscale("log") if self.axis2: self.axis2.set_yscale("log") except AttributeError: pass
def plot_mds_all(plot_arg, plot_output_arg, name): _, axf = plt.subplots(figsize=(10, 10)) first_arg = [arg[0] for arg in plot_arg] second_arg = [arg[1] for arg in plot_arg] output_first_arg = [arg[0] for arg in plot_output_arg] output_second_arg = [arg[1] for arg in plot_output_arg] sorted_target_first = [] sorted_target_second = [] sorted_output_first = [] sorted_output_second = [] for tar2, tar1, out1, out2 in sorted(zip(second_arg, first_arg, output_first_arg, output_second_arg)): sorted_target_first.append(tar1) sorted_target_second.append(tar2) sorted_output_first.append(out1) sorted_output_second.append(out2) colors = [x for x in range(len(second_arg))] axf.scatter(sorted_target_first, sorted_target_second, c=colors, cmap=plt.hot(), edgecolors='black', linewidth=2) axf.scatter(sorted_output_first, sorted_output_second, c=colors, cmap=plt.hot(), edgecolors='blue', linewidth=2) axf.set_ylabel("output var 1") axf.set_xlabel("output var 2") plt.tight_layout() plt.savefig("plot/plots/" + name + ".png", dpi=400)
def im_show(self, raster): data = None data = raster pyplot.hot() pyplot.imshow(data < 40) # figura 1 pyplot.title('ndvi') #pyplot.colorbar() fig1 = pyplot.figure() ax1 = fig1.add_subplot(111) ax1.set_ylabel('lat') ax1.set_xlabel('long') ax1.set_title('imagen test') dataflt = self.im_dilate(data < 40, 3) ax1.imshow(dataflt) #pyplot.subplot(2,2,1) #pyplot.imshow((data > 0.5) * data) #pyplot.subplot(2,2,4) #hist,bins = numpy.histogram(data,bins=255) #width = 0.2*(bins[1]-bins[0]) #center = (bins[:-1]+bins[1:])/2 #ax2 = fig2.add_subplot(111) #ax2.set_title('histograma de la imagen') #x2.set_xlabel('valores digitales') #ax2.set_ylabel('cuentas') #ax2.bar(center, hist, align = 'center', width = width) #pyplot.bar(center, hist, align = 'center', width = width) pyplot.show()
def plot_population_tuples_3d(self): count_dict = dict() for fit in self.population_fitness: if fit not in count_dict: count_dict[fit] = 1 else: count_dict[fit] = count_dict[fit] + 1 # count_dict = {fit: len(val) for fit, val in count_dict} fit1 = [] fit2 = [] fit3 = [] counts = [] for fit, count in count_dict.items(): fit1.append(fit[0]) fit2.append(fit[1]) fit3.append(fit[2]) counts.append(count) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') plt.hot() ax.scatter(np.array(fit1), np.array(fit2), np.array(fit3), c=np.array(counts)) graph = plt.show(block=True) with open(plot_population_3d, 'wb') as f: pickle.dump(graph, f)
def plot_spectrum(ham,klen,xticks,mu,eta0=5.e-2,de=100,smesh=200): """ This function plot spaghetti like spectrum. arguments: ham: hamiltonian array klen: coordinates of horizontal axis mu: chemical potential de: energy mesh (optional, default=100) eta: eta for green function (optional, default=5e-2) smesh: contor mesh (optional, default=200) """ emax,emin=gen_eig(ham,mass,mu,False) w=np.linspace(emin*1.1,emax*1.1,de) no=len(ham[0]) #eta=w*0+eta0 etamax=4.0e0 eta=etamax*w*w/min(emax*emax,emin*emin)+eta0 G=np.array([[-sclin.inv((ww+mu+et*1j)*np.identity(no)-h) for h in ham] for ww,et in zip(w,eta)]) trG=np.array([[np.trace(gg).imag/(no*no) for gg in g] for g in G]) sp,w=np.meshgrid(klen,w) plt.hot() plt.contourf(sp,w,trG,smesh) plt.colorbar() for x in xticks[1:-1]: plt.axvline(x,ls='-',lw=0.25,color='black') plt.xlim(0,klen.max()) plt.axhline(0.,ls='--',lw=0.25,color='black') plt.xticks(xticks,xlabel) plt.show()
def preparePlot(self): """Prepare the plotting window""" plt.hot() self.figure = plt.figure(self.figNr) self.figure.clear() # this is black magic that makes the legend work with two axes if self.hasSubplotHost: self.axis1 = SubplotHost(self.figure, 111) self.figure.add_subplot(self.axis1) else: self.axis1 = self.figure.add_subplot(111) self.axis1.set_xlabel(self.xlabel) self.axis1.set_ylabel(self.ylabel) if len(self.alternate) > 0: self.axis2 = self.axis1.twinx() self.axis2.set_ylabel(self.ylabel2) try: if self.spec.logscale: self.axis1.set_yscale("log") if self.axis2: self.axis2.set_yscale("log") except AttributeError: pass
def replot(self): plot.axes(imgframe) plot.cla() plot.hot() thetai = (pi / 2) * self.idx / (self.mx + 1.0) plot.title("Shadowing function $\\theta_i = %.1f^\circ$" % (degrees(thetai))) plot.imshow(Hemi[self.idx,:,:], interpolation="nearest") plot.contour(self.X, self.Y, Hemi[self.idx,:,:], levels=arange(0.0,1.0,0.1), colors="black") plot.draw()
def plotting_sm(data): data = np.array(data) data.shape = (9, 9) plt.hot() plt.pcolormesh(data) #plt.colorbar() plt.xticks(np.arange(9), ('.1', '.2', '.3', '.4', '.5', '.6', '.7', '.8', '.9')) #plt.yticks(np.arange(9), ('.1', '.2', '.3', '.4', '.5', '.6', '.7', '.8', '.9')) plt.xlabel('sm12') plt.ylabel('sm11')
def run_valid(dimensions,steps,timesteps, time_interval,diffusivity): """This function serves as a validation of the Crank-Nicolson numerical method implemented in this program. This function produces both the numerical results and the analytical results for the solution of the heat equation of a 2Dimensional unit square with the initial tempereture given by the funciton T(x,y)=x+y. The analytical solution used here is the fourier analysis solution for the heat equation in the unit square. Arguments: dimensions(float): dimension of square(1 for this funciton) steps(integer): number of grid steps timesteps(integer): number of time steps time_interval(tuple): interval of time starting from time of initial condition diffusivity(float): Thermal diffusivity Returns: None """ (a,b) = time_interval times = np.linspace(a,b,timesteps) timestep =(b-a)/timesteps T_initial = initial_function(steps) matrices = configure_matrix(steps,timestep,dimensions,diffusivity) solution = solve(matrices,T_initial,timesteps,50) solution_valid = validation(steps,time_interval,timesteps,diffusivity) for i in range(timesteps): data =solution[:,i] data=np.reshape(data,(steps,steps)) pylab.imshow(data) plt.hot() cbar=plt.colorbar() cbar.set_label('Temperature') title = 'Time:' + str(times[i]) + 's' plt.title(title) plt.xlabel('x') plt.ylabel('y') pylab.show() for i in range(timesteps): data =solution_valid[:,i] data=np.reshape(data,(steps,steps)) pylab.imshow(data) plt.hot() #cbar=plt.colorbar() #cbar.set_label('Temperature') title = 'VALID solution' +'Time:' + str(times[i]) + 's' plt.title(title) plt.xlabel('x') plt.ylabel('y') pylab.show()
def plotbcomp(beamx_m,beamy_m,beams_m,beamx_t,beamy_t,beams_t): print 'Plotting beams...' plot.figure(1,figsize=(7,10)) plot.clf() plot.hot() tit=('PSW','PMW','PLW') for b in arange(3): pnum_m=2*b+1 pnum_t=2*b+2 #margins ym=1.1 xm=1.0 #color levels ncol=16 ntick=8 pl_m=array([-8.,0]) pl_t=array([-8.,0]) pr_m=pl_m[1]-pl_m[0] pr_t=pl_t[1]-pl_t[0] cl_m=arange(pl_m[0],pl_m[1]+pr_m/ncol,pr_m/ncol) cl_t=arange(pl_t[0],pl_t[1]+pr_t/ncol,pr_t/ncol) tl_m=arange(pl_m[0],pl_m[1]+pr_m/ntick,pr_m/ntick) tl_t=arange(pl_t[0],pl_t[1]+pr_t/ntick,pr_t/ntick) plot.subplot(3,2,pnum_m) plot.axis('equal') plot.contourf(beamx_m,beamy_m,log10(beams_m[:,:,b]),levels=cl_m) plot.xlim((xm*min(beamx_m),xm*max(beamx_m))) if b==2: plot.xticks((floor(min(beamx_m)),0,ceil((max(beamx_m))))) plot.xlabel('x ["]') else:plot.xticks((floor(min(beamx_m)),0,ceil((max(beamx_m)))),('','','')) plot.ylim((ym*min(beamy_m),ym*max(beamy_m))) plot.yticks((floor(min(beamy_m)),0,ceil((max(beamy_m)))),rotation=90) plot.ylabel(tit[b]) if b==0: plot.title('Measured') plot.colorbar(format='%.1f',ticks=tl_m) plot.subplot(3,2,pnum_t) plot.axis('equal') plot.contourf(beamx_t,beamy_t,log10(beams_t[:,:,b]),levels=cl_t) plot.xlim((xm*min(beamx_t),xm*max(beamx_t))) if b==2: plot.xticks((floor(min(beamx_t)),0,ceil((max(beamx_t))))) plot.xlabel('x ["]') else: plot.xticks((floor(min(beamx_t)),0,ceil((max(beamx_t)))),('','','')) plot.ylim((ym*min(beamy_t),ym*max(beamy_t))) plot.yticks((floor(min(beamy_t)),0,ceil((max(beamy_t)))),('','',''),rotation=90) if b==0: plot.title('Theoretical') plot.colorbar(format='%.1f',ticks=tl_t)
def generateAndSampleTwoClasses(m0, c0, m1, c1): """ Creates two Gaussian distributions with given means and covariances. :param m0: mean of first distribution :param c0: coveriance matrix of first distribution :param m1: mean of second distribution :param c1: coveriance matrix of second distribution :return: [distribution1, distribution2, SAMPLE_NO_0 of samples from distribution1, SAMPLE_NO_1 of samples from distribution2] """ # generate samples that fit class conditional distribution of class 0 # p(x|L=0) -> 4D random vector x|L=0 dist0 = multivariate_normal(m0, c0) xl0 = dist0.rvs(size=SAMPLE_NO_0) # generate samples that fit class conditional distribution of class 0 # p(x|L=1) -> 4D random vector dist1 = multivariate_normal(m1, c1) xl1 = dist1.rvs(size=SAMPLE_NO_1) # xl0[:, k] returns kth columns of xl0 # plot each column one a separate axis, with the exception with the last, which is plotted as a # color fig = plt.figure(0) # xl0 plot ax0 = fig.add_subplot(1, 2, 1, projection='3d') ax0.title.set_text('samples of X for class 0') ax0.set_xlabel('x0') ax0.set_ylabel('x1') ax0.set_zlabel('x2') img0 = ax0.scatter(xl0[:, 0], xl0[:, 1], xl0[:, 2], c=xl0[:, 3], cmap=plt.hot()) fig.colorbar(img0) # xl1 plot ax1 = fig.add_subplot(1, 2, 2, projection='3d') ax1.title.set_text('samples of X for class 1') ax1.set_xlabel('x0') ax1.set_ylabel('x1') ax1.set_zlabel('x2') img1 = ax1.scatter(xl1[:, 0], xl1[:, 1], xl1[:, 2], c=xl1[:, 3], cmap=plt.hot()) fig.colorbar(img1) return dist0, dist1, xl0, xl1
def Intensite(self,num=0): ''' plot l'intensité ''' #le champ E a un pont de moins, on recupere les bons x x0=EMpy.utils.centered1d(self.x) y0= EMpy.utils.centered1d(self.y) Itot=np.abs(self.sol.modes[num].intensity()) fig = plt.figure() plt.hot() levels=np.unique([1,self.nc2,self.n1B2,self.n1C2,self.n2B2,self.n2C2,self.ns2]) Nlevel=15 plt.contour(self.x,self.y,self.epsfunc(self.x,self.y).T,levels,colors='white') plt.contourf(x0,y0 ,Itot.T, Nlevel) print("%Conf: {:.2f}".format(100*self.Confinement(num=num))) print("%TE: {:.1f}".format(100*self.sol.modes[num].TEfrac()))
def graficar_3d(): # Se grafica el potencial, con colores que indican la intensidad de este fig = plt.figure() ax = fig.add_subplot(111, projection='3d') img = ax.scatter(X, Y, Z, c=P, cmap=plt.hot(), marker='o') fig.colorbar(img) plt.show() plt.close() # Grafica la solucion obtenida numericamente fig = plt.figure() ax = fig.add_subplot(111, projection='3d') img = ax.scatter(X, Y, Z, c=data, cmap=plt.hot(), marker='o') fig.colorbar(img) plt.show() plt.close()
def MyAnimation(): fig = plt.figure() ax = fig.gca(projection='3d') #ax = fig.add_subplot(111, projection='3d') df = pd.read_csv('data.csv') print(df) x = df['diam'] y = df['length'] #z = df['br1'] z = df['gauss'] ax.set_xlabel('diameter') ax.set_ylabel('length') ax.set_zlabel('br') ax.set_title('Magnetic Field Calculations') #img = ax.scatter(x, y, z, c='blue', cmap=plt.hot()) camera = Camera(fig) for i in df['br']: ax.set_title('Magnetic Field Calculations: {} br '.format(int(i))) # ax.plot_scatter(df['length'], df['diameter'], df['br'], c='r', linewidth=0.2) #cmap=plt.get_cmap('viridis'), linewidth=0.2) img = ax.scatter(x, y, z, c='blue', cmap=plt.hot()) camera.snap() animation = camera.animate() animation.save('celluloid_minimal.gif', writer='imagemagick')
def plot_3d_scatter(df): print("func called") for frequency in FREQUENCIES: df_temp = df.loc[df['Frequency'] == frequency] for stage in STAGES: fig = plt.figure() ax = Axes3D(fig) title = "4D plot for Frequency: " + str( frequency) + " Stage: " + stage fig.suptitle(title) stage_on_source_time = stage + '_on_source_time' stage_flux = stage + '_flux' stage_clean = stage + '_clean_components' stage_rms = stage + '_rms' x = df_temp[stage_on_source_time] y = df_temp[stage_rms] z = df_temp[stage_clean] c = df_temp[stage_flux] xlabel = stage + "on_source_time" ylabel = stage + "rms" zlabel = stage + "clean_components" ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.set_zlabel(zlabel) sc = ax.scatter(x, y, z, c=c, cmap=plt.hot()) plt.colorbar(sc) plt.show()
def show3d_character(img_3d, title): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.grid(False) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') ax.set_xlim(0, 15) ax.set_ylim(0, 15) ax.set_zlim(0, 15) ax.set_title(title) box_size = 16 x = [] y = [] z = [] for i in range(box_size): for j in range(box_size): for k in range(box_size): if img_3d[j,i,k] > 0.1: x.append(i) y.append(j) z.append(k) img = ax.scatter( z, x, y, c=img_3d[x,y,z],s=10, cmap=plt.hot()) fig.colorbar(img) plt.show()
def plot4D(X, Y, Z, A, labelX, labelY, labelZ, figSaveName, labelA="variation"): plt.gcf().clear() fig = plt.figure() ax = fig.add_subplot(111, projection='3d') cartesian = np.array([[x, y, z] for x in X for y in Y for z in Z]) plt.gca().invert_yaxis() sp = ax.scatter(cartesian[:, 0], cartesian[:, 1], cartesian[:, 2], c=A, cmap=plt.hot(), marker="h") ax.set_xlabel(labelX) ax.set_ylabel(labelY) ax.set_zlabel(labelZ) bar = plt.colorbar(sp) bar.set_label(labelA) plt.savefig(figSaveName + ".pdf") plt.show() return
def createIntersectionZ(self, a): pomX = [] pomY = [] pomZ = [] pomT = [] minZ = min(self.Z) maxZ = max(self.Z) intesectionTab_z = np.linspace(minZ, maxZ, 11) for i in range(len(self.X)): if (self.Z[i] > intesectionTab_z[a] and self.Z[i] < intesectionTab_z[a + 1]): pomX.append(self.X[i]) pomY.append(self.Y[i]) pomZ.append(self.Z[i]) pomT.append(self.T[i]) fig = plt.figure() ax = fig.gca(projection='3d') img = ax.scatter(pomX, pomY, 0, c=pomT, cmap=plt.hot()) fig.colorbar(img) plt.xlabel("x") plt.ylabel("y") # plt.axis('off') plt.show()
def createIntersectionY(self, a): pomX = [] pomY = [] pomZ = [] pomT = [] minY = min(self.Y) maxY = max(self.Y) intesectionTab_y = np.linspace(minY, maxY, 11) for i in range(len(self.X)): if (self.Y[i] > intesectionTab_y[a] and self.Y[i] < intesectionTab_y[a + 1]): pomX.append(self.X[i]) pomY.append(self.Y[i]) pomZ.append(self.Z[i]) pomT.append(self.T[i]) fig = plt.figure() ax = fig.gca(projection='3d') img = ax.scatter(pomX, 0, pomZ, c=pomT, cmap=plt.hot()) fig.colorbar(img) plt.xlabel("x") plt.ylabel("y") #ax.set_xlim([min(self.X), max(self.X)]) #ax.set_ylim([min(self.Y) - 20*abs(max(self.Y) - min(self.Y)) , max(self.Y)]) #print (max(self.Y)) #print(min(self.Y)) #ax.set_ylim([ymin, ymax]) #plt.axis('off') plt.show()
def plotPoints(points): N, D = points.shape D = D - 1 if D == 1: plt.plot(points[:, [0]], points[:, [1]]) plt.xlabel('points - x') plt.ylabel('weights') plt.show() elif D == 2: x, y, z = points[:, [0]].reshape(1, N), points[:, [1]].reshape( 1, N), points[:, [2]].reshape(1, N) df = pd.DataFrame({'x': x[0], 'y': y[0], 'z': z[0]}) fig = plt.figure() ax = Axes3D(fig) surf = ax.plot_trisurf(df.x, df.y, df.z, cmap=cm.jet, linewidth=0.1) fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() elif D == 3: fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = points[:, [0]].reshape(1, N)[0] y = points[:, [1]].reshape(1, N)[0] z = points[:, [2]].reshape(1, N)[0] c = points[:, [3]].reshape(1, N)[0] sp = ax.scatter(x, y, z, c=c, cmap=plt.hot()) plt.colorbar(sp) plt.show() else: raise Exception( "Plotter cannot visualize data higher than 3 Dimensions")
def plot_4d(data, plane=False): """ plots four dimensional data of a given dataframe, data, in three dimensional space and a color space. 1st column is the x axis, 2nd y axis, 3rd z axis, and the fourth is the color. if plane = true fits a plane to the data and plots it """ fig = plt.figure("4d_parameters") ax = fig.add_subplot(111, projection='3d') x = data.iloc[:,0] y = data.iloc[:,1] z = data.iloc[:,2] c = data.iloc[:,3] ax.scatter(x, y, z, c=c, cmap=plt.hot()) if(plane): # plot plane fit=fit_plane(data) xlim = ax.get_xlim() ylim = ax.get_ylim() X,Y = np.meshgrid(np.arange(xlim[0], xlim[1]), np.arange(ylim[0], ylim[1])) Z = np.zeros(X.shape) for r in range(X.shape[0]): for c in range(X.shape[1]): Z[r,c] = fit[0] * X[r,c] + fit[1] * Y[r,c] + fit[2] ax.plot_wireframe(X,Y,Z, color='k') plt.show()
def plotData(x, y, z, c, title): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') img = ax.scatter(x, y, z, c=c, cmap=plt.hot()) fig.colorbar(img) plt.title(title) plt.show()
def TraceMode(self,num=0): ''' trace les 6 composantes du champ ''' Nlevel=15 levels=np.unique([1,self.nc2,self.n1B2,self.n1C2,self.n2B2,self.n2C2,self.ns2]) #le champ E a un pont de moins, on recupere les bons x x0=EMpy.utils.centered1d(self.x) y0= EMpy.utils.centered1d(self.y) fig = plt.figure(figsize=(12, 6)) plt.hot() fig.add_subplot(2, 3, 1) plt.contour(self.x,self.y,self.epsfunc(self.x,self.y).T,levels,colors='white') plt.contourf(x0,y0,abs(self.sol.modes[num].Ex).T, Nlevel) plt.title('Ex') plt.colorbar() fig.add_subplot(2, 3, 2) plt.contour(self.x,self.y,self.epsfunc(self.x,self.y).T,levels,colors='white') plt.contourf(x0,y0,abs(self.sol.modes[num].Ey).T, Nlevel) plt.title('Ey') plt.colorbar() fig.add_subplot(2, 3, 3) plt.contour(self.x,self.y,self.epsfunc(self.x,self.y).T,levels,colors='white') plt.contourf(x0,y0,abs(self.sol.modes[num].Ez).T, Nlevel) plt.title('Ez') plt.colorbar() fig.add_subplot(2, 3, 4) plt.contour(self.x,self.y,self.epsfunc(self.x,self.y).T,levels,colors='white') plt.contourf(self.x,self.y,abs(self.sol.modes[num].Hx).T, Nlevel) plt.title('Hx') plt.colorbar() fig.add_subplot(2, 3, 5) plt.contour(self.x,self.y,self.epsfunc(self.x,self.y).T,levels,colors='white') plt.contourf(self.x,self.y,abs(self.sol.modes[num].Hy).T, Nlevel) plt.title('Hy') plt.colorbar() fig.add_subplot(2, 3, 6) plt.contour(self.x,self.y,self.epsfunc(self.x,self.y).T,levels,colors='white') plt.contourf(self.x,self.y,abs(self.sol.modes[num].Hz).T, Nlevel) plt.title('Hz') plt.colorbar() plt.show()
def plot_progress_4d(save_folder, points_to_sample, num_samples, posterior_model, pref_num, reward_models, dim_to_keep): # Unpack model posterior: post_mean = posterior_model['mean'] cov_evecs = np.real(posterior_model['cov_evecs']) cov_evals = posterior_model['cov_evals'] # Construct posterior covariance matrix: post_cov = cov_evecs @ np.diag(cov_evals) @ np.linalg.inv(cov_evecs) # Posterior standard deviation at each point: post_stdev = np.sqrt(np.diag(post_cov)) plt.figure(figsize=(8, 6)) # x_values = [point[dim_to_keep] for point in points_to_sample] #what about visited points? x = [point[0] for point in points_to_sample] y = [point[1] for point in points_to_sample] z = [point[2] for point in points_to_sample] fig = plt.figure() # plt.fill_between(x_values, post_mean - 2*post_stdev, # post_mean + 2*post_stdev, alpha = 0.3, color = 'blue') ax = fig.add_subplot(111, projection='3d') img = ax.scatter(x, y, z, c=post_mean, cmap=plt.hot()) # Plot posterior samples: for j in range(num_samples): print(len(reward_model)) reward_model = reward_models[j] ax.scatter( x, y, z, c=reward_model, cmap=plt.hot(), linestyle='--', ) plt.tight_layout() fig.colorbar(img) plt.savefig(save_folder + '4d_test_' + str(pref_num) + \ '_preferences_' + str(time.time())[-3:] + '.png')
def plott_one(arr, sizes, name, path, timestep, cell_length): di = {} di['time'] = 'ms' di['temperature'] = 'K' di['pressure'] = 'Pa' di['velocity'] = r'$\rm m \cdot s^{-1}$' di['density'] = r'$\rm kg \cdot m^{-3}$' prename = path+"/"+name steps, size = sizes fs = [10,10] pyplot.figure(figsize = (fs[0],fs[1])) pyplot.imshow(arr, extent=[0,size*cell_length,0,steps*timestep*1000], aspect='auto', interpolation = 'none') pyplot.hot() pyplot.xlabel("position [m]", fontsize = 20) pyplot.ylabel("time [ms]", fontsize = 20) pyplot.tick_params(axis='both', which='major', labelsize=15) pyplot.tick_params(axis='both', which='minor', labelsize=12) cbar = pyplot.colorbar() cbar.set_label(name+' ['+di[name]+']', rotation=90, fontsize = 20) pyplot.savefig(prename+"_no_interp.pdf") pyplot.cla() pyplot.clf() fs = [10,10] pyplot.figure(figsize = (fs[0],fs[1])) pyplot.imshow(arr, extent=[0,size*cell_length,0,steps*timestep*1000], aspect='auto') pyplot.hot() pyplot.xlabel("position [m]", fontsize = 20) pyplot.ylabel("time [ms]", fontsize = 20) cbar = pyplot.colorbar() cbar.set_label(name+' ['+di[name]+']', rotation=90, fontsize = 20) pyplot.savefig(prename+"_interp.pdf")
def __init__(self, data=None, params=None): super(DDMPlot, self).__init__() plt.hot() # Create plot self.num_axes = 3 self.ax1 = self.figure.add_subplot(411) self.ax2 = self.figure.add_subplot(412, sharex=self.ax1) self.ax3 = self.figure.add_subplot(413, sharex=self.ax1) self.set_figure() #self.update_plot() # Set external data if necessary if data is not None: self.data = data if params is not None: self._set_external_params(params)
def plotting_wp(data, wp, min_max): data = np.array(data) dim = int(math.sqrt(data.size)) data.shape = (dim, dim) plt.hot() plt.pcolormesh(data) #plt.colorbar() #plt.clim(min_max[0], min_max[1]) plt.xticks(np.arange(9), ('.1', '.2', '.3', '.4', '.5', '.6', '.7', '.8', '.9')) plt.yticks(np.arange(9), ('.1', '.2', '.3', '.4', '.5', '.6', '.7', '.8', '.9')) if wp == 0.9: plt.colorbar() plt.clim(min_max[0], min_max[1]) if wp in [.7, .8, .9]: plt.xlabel('sm12') if wp in [.1, .4, .7]: plt.ylabel('sm11') plt.title(str(wp), fontsize='small')
def createSPHChart3D(self): fig = plt.figure() ax = fig.gca(projection='3d') img = ax.scatter(self.X, self.Y, self.Z, c=self.T, cmap=plt.hot()) fig.colorbar(img) plt.xlabel("x") plt.ylabel("y") plt.axis('off') plt.show()
def plot_stm(ground_state_file, bias, z): calc = GPAW(ground_state_file, txt="graphene_stm.txt") stm = STM(calc.get_atoms()) # Get the average constant-height (height = z) current for a reasonable value # of the current to use when scanning. c = stm.get_averaged_current(bias, z) # Scan over the unit cell at constant current. # repeat=(3, 5) --> repeat over 3 copies of unit cell in one direction, 5 in another x, y, h = stm.scan(bias, c, repeat=(3, 5)) plt.gca(aspect='equal') plt.contourf(x, y, h, 80) # 80 contour levels plt.hot() plt.colorbar() plt.savefig("graphene_stm_bias_{:.2f}_z_{:.2f}.png".format(bias, z), bbox_inches='tight', dpi=500) plt.clf()
def plot(self, func, interp=True, plotter='imshow'): if interp: lpi = self.interpolator(func) z = lpi[self.yrange[0]:self.yrange[1]:complex(0, self.nrange), self.xrange[0]:self.xrange[1]:complex(0, self.nrange)] else: y, x = np.mgrid[ self.yrange[0]:self.yrange[1]:complex(0, self.nrange), self.xrange[0]:self.xrange[1]:complex(0, self.nrange)] z = func(x, y) z = np.where(np.isinf(z), 0.0, z) extent = (self.xrange[0], self.xrange[1], self.yrange[0], self.yrange[1]) fig = plt.figure() plt.hot() # Some like it hot if plotter == 'imshow': plt.imshow(np.nan_to_num(z), interpolation='nearest', extent=extent, origin='lower') elif plotter == 'contour': Y, X = np.ogrid[ self.yrange[0]:self.yrange[1]:complex(0, self.nrange), self.xrange[0]:self.xrange[1]:complex(0, self.nrange)] plt.contour(np.ravel(X), np.ravel(Y), z, 20) x = self.x y = self.y lc = mpl.collections.LineCollection(np.array([ ((x[i], y[i]), (x[j], y[j])) for i, j in self.tri.edge_db ]), colors=[(0, 0, 0, 0.2)]) ax = plt.gca() ax.add_collection(lc) if interp: title = '%s Interpolant' % self.name else: title = 'Reference' if hasattr(func, 'title'): plt.title('%s: %s' % (func.title, title)) else: plt.title(title)
def diffraction(wavelength): import numpy as np k = 2 * np.pi / wavelength # wavenumber # a function compute I, intenisty at a given distance def I_r(r): J1 = Jm(1, k * r) I = (J1 / k / r)**2 return I ## a gird of x and y axis covers 1miu m from the origin x_axis = np.linspace(-1.E-6, 1.E-6, 101) y_axis = np.linspace(-1.E-6, 1.E-6, 101) I = np.zeros((101, 101)) # a 2D array to hold the results of I n_x = 0 ## track column number in the 2D data array for x in x_axis: n_y = 0 # track row number in the 2D data array for y in y_axis: r = np.sqrt(x**2 + y**2) #compute the distance to origin if (r != 0): In = I_r(r) # compute I I[n_x][n_y] = In #update I ## I(r) is not defined at r=0, use approximation instead else: I[n_x][n_y] = 0.5**2 # approximation of I(r) when r =0 n_y += 1 # go on to the next row n_x += 1 # to the next column # plot 2D diffractio result plt.imshow(I, origin="lower", vmax=1.0E-2, extent=[-1, 1, -1, 1]) ## vmax =1.0E-2 for adjustment to show the pattern plt.title("Density Plot of Intensity") plt.ylabel("$y(\mu m)$") plt.xlabel("$x(\mu m)$") plt.hot() plt.savefig("diffraction.pdf") plt.show()
def contour_plot(self, sensors=[0.2, 0.2, 0.2, 0.0], title="Contour Plot of Q(s,a)"): # # Show a contour plot of how Q varies over the geometry of our # play area, while fixing sensor readings and car rotation. # x, y, z = self.location_contours(sensors) plt.figure(facecolor='white') plt.hot() im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno) CBI = plt.colorbar(im, orientation='horizontal', shrink=0.8) plt.title(title + ": theta=" + str(int(sensors[3] * 180.0 / np.pi))) plt.xlabel('x%') plt.ylabel('y%') plt.show()
def plt_overview(dimension, coords, roi): # roi rectangle mybox=np.array([[roi[0],roi[0], roi[1], roi[1], roi[0]],[roi[2],roi[3],roi[3],roi[2],roi[2]]]) #construct image from coordinates zoom_factor = 8 im = cr.coords2Image(dimension, coords, zoom_factor) #plot plt.figure() plt.title("Storm image: " + overviewfile) plt.imshow(im) plt.hot() #colormap # rescale roi rectangle and plot it into the image mybox=zoom_factor*mybox plt.plot(mybox[0,...], mybox[1,...], '0.3') plt.axis([0,dimension[0]*zoom_factor,0,dimension[1]*zoom_factor]) plt.colorbar()
def angle_v_sensor_plot(self, x0=0.5, y0=0.5, title="Contour Plot of Q(s,a)"): # # Show a contour plot of how Q varies as we change car rotation # and sensor strength at a fixed position (x0,y0) in the game area. # x, y, z = self.angle_v_sensor_contours(x0, y0) plt.figure(facecolor='white') plt.hot() plt.xlabel('Orientation') plt.ylabel('Signal strength') im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno) CBI = plt.colorbar(im, orientation='horizontal', shrink=0.8) plt.title(title) plt.show()
def plot4(x, y, z, c, title): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') img = ax.scatter(x, y, z, c=c, cmap=plt.hot()) fig.colorbar(img) ax.set_xlabel('Die 1') ax.set_ylabel('Die 2') ax.set_zlabel('Die 3') ax.set_title(title) return fig, ax
def make_4d_plot_of_data(self, data, target): data.replace({"A": 1, "B": 2, "C": 3}, inplace=True) x = data["month"] y = data["customer"] z = data["item"] fig = plt.figure() ax = fig.add_subplot(111, projection='3d') img = ax.scatter(x, y, z, c=target, cmap=plt.hot()) fig.colorbar(img) plt.show()
def plot_simulate_dn(self): '''This method plots modal birefringence of the simulated data in the file called by the method fileDialog''' self.create_Entrys() fig, ax = plt.subplots(figsize=(8, 6)) #plt.title("Modal bireferengence as a function of channel dimensions") im = plt.imshow(self.dr, extent=[self.LC_1, self.LC_2, self.H1_1, self.H1_2], origin='lower') plt.xlabel("H1 (\u03BCm)") plt.ylabel("LC (\u03BCm)") divider = make_axes_locatable(ax) cax = divider.new_vertical(size="5%", pad=0.4, title="Modal bireferengence") fig.add_axes(cax) fig.colorbar(im, cax=cax, orientation="horizontal") # plt.savefig('colorbar_positioning_03.png', format='png', bbox_inches='tight') plt.hot() plt.show() plt.close()
def plot_Q_value(ax, agent_critic_Q, states, actions): X, Y, Z, Q = [], [], [], [] with torch.no_grad(): for x in states[0]: for y in states[1]: for z in actions: X.append(x), Y.append(y), Z.append(z) in_state = torch.as_tensor(list(zip(X, Y)), dtype=torch.float32) in_action = torch.as_tensor(Z, dtype=torch.float32).unsqueeze(-1) Q = agent_critic_Q(in_state, in_action).numpy() return ax.scatter(X, Y, Z, c=Q, cmap=plt.hot())
def plot2Dimage(image, picker=False, show=True, block=True, clim=None, alpha=1): """ Plots the image as a 2D plot. If the color limits are given, some hopefully useful default limits are calculated and used. This function is intended for basic plotting purposes. :param image: :param picker: :param show: :param block: :param clim: :return: """ #cmap = mpl.colors.Colormap('afmhot', N=512) #cmap.set_bad(color=u'k', alpha=None) # This code tries to make the default color limits sensible with most scattering data if not clim: min_val = np.amin(image) image_corr = image - min_val + 1 image_corr = np.log(image_corr) median_val = np.median(image_corr) max_val = np.amax(image_corr) cmin_val = median_val cmax_val = max_val clim = (cmin_val, cmax_val) else: image_corr = np.log(image+1) plt.imshow(image_corr, picker=picker, interpolation='none', alpha=alpha) # adjust colormap plt.hot() plt.clim(clim) if show: plt.show(block=block) return plt
def plot(self, func, interp=True, plotter='imshow'): if interp: lpi = self.interpolator(func) z = lpi[self.yrange[0]:self.yrange[1]:complex(0,self.nrange), self.xrange[0]:self.xrange[1]:complex(0,self.nrange)] else: y, x = np.mgrid[self.yrange[0]:self.yrange[1]:complex(0,self.nrange), self.xrange[0]:self.xrange[1]:complex(0,self.nrange)] z = func(x, y) z = np.where(np.isinf(z), 0.0, z) extent = (self.xrange[0], self.xrange[1], self.yrange[0], self.yrange[1]) fig = plt.figure() plt.hot() # Some like it hot if plotter == 'imshow': plt.imshow(np.nan_to_num(z), interpolation='nearest', extent=extent, origin='lower') elif plotter == 'contour': Y, X = np.ogrid[self.yrange[0]:self.yrange[1]:complex(0,self.nrange), self.xrange[0]:self.xrange[1]:complex(0,self.nrange)] plt.contour(np.ravel(X), np.ravel(Y), z, 20) x = self.x y = self.y lc = mpl.collections.LineCollection(np.array([((x[i], y[i]), (x[j], y[j])) for i, j in self.tri.edge_db]), colors=[(0,0,0,0.2)]) ax = plt.gca() ax.add_collection(lc) if interp: title = '%s Interpolant' % self.name else: title = 'Reference' if hasattr(func, 'title'): plt.title('%s: %s' % (func.title, title)) else: plt.title(title)
def toImage(image_data): """ @param image_data uint16 array containing intensities from binary files This function converts the intensity data from all files into high-res and low-res images. """ """ Plots the intensity data using matplotlib; faster but high resolution is lost """ # Removes values below a threshold to make the background of the ring images # black image_data.shape = size plt.imshow(np.minimum(stats.threshold(image_data,threshmin=threshold, newval=0), 255 + 0*image_data)) # Specifies the color map; can be modified if you want! plt.hot() plt.grid() # Saves image to output directory plt.savefig(imDirectory + output + "-lo.png") """ Plots the intensity map by converting intensities to RGB values; slower but has higher resolution """ # Determines max intensity for the gradient maxI = np.max(image_data) # creates an mxnx3 array of zeros of type uint8; this array will store # the RGB values that will be converted to an image rgbArr = np.zeros((size[0],size[0],3),dtype = 'uint8') sys.stdout.write("Converting to Image\n") for i in range(size[0]): for j in range(size[0]): # Converts intensity to pixel rgbArr[i,j] = toRGB(image_data[i][j],maxI) image = Image.fromarray(rgbArr,'RGB') # Saves image to output director provided image.save(imDirectory + output + ".png")
def plot3dmap(self, data, maskvalue=50000, multiple=False, fig=None): plt.clf() if len(data) <= 0: return zlayers = [] for entry in data: #read each file and load it zlayers += [numpy.load(entry)] #prepare the x-axes (since we have a rectangle we have height times the same x value) xdim = zlayers[0].shape[0] ydim = zlayers[0].shape[1] zdim = len(zlayers) x_ = numpy.linspace(1,xdim, xdim) y_ = numpy.linspace(1,ydim, ydim) z_ = numpy.linspace(1,zdim, zdim) x,y,z = numpy.meshgrid(x_,y_,z_, indexing='ij') vol = xdim * ydim * zdim x = x.reshape(vol,) y = y.reshape(vol,) z = z.reshape(vol,) c = numpy.array(zlayers) c = c.reshape(xdim*ydim*zdim,order='F') c = numpy.ma.masked_less(c, maskvalue) print("shapes", x.shape, y.shape,z.shape, c.shape) #now we have prepared our data lets plot from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np #if not multiple we get a figure object so add our plot as a add_subplot if not multiple: fig = plt.figure(1) ax = fig.add_subplot(111, projection='3d') sc = ax.scatter(x,y,z,c=c, cmap=plt.hot()) plt.colorbar(sc) #if we have multiple ones, we dont want to show the plot if not multiple: plt.show() plt.savefig("3dplot.jpeg")
def plot3dmap(data, maskvalue=50000, plotid=111, title=""): global fig if len(data) <= 0: return zlayers = [] for entry in data: #read each file and load it zlayers += [numpy.load(entry)] #prepare the x-axes (since we have a rectangle we have height times the same x value) xdim = zlayers[0].shape[0] ydim = zlayers[0].shape[1] zdim = len(zlayers) x_ = numpy.linspace(1,xdim, xdim) y_ = numpy.linspace(1,ydim, ydim) z_ = numpy.linspace(1,zdim, zdim) x,y,z = numpy.meshgrid(x_,y_,z_, indexing='ij') vol = xdim * ydim * zdim x = x.reshape(vol,) y = y.reshape(vol,) z = z.reshape(vol,) print(x,y,z) #for xval in numpy.linspace(1,xdim,xdim): # print(len(ydim* zdim *[xval])) # x = numpy.append(x,ydim* zdim *[xval]) #for yval in numpy.linspace(1,ydim,ydim): # y = numpy.append(y,xdim *zdim * [yval]) # for zval in numpy.linspace(1,zdim,zdim): # z = numpy.append(z,xdim *ydim * [zval]) c = numpy.array(zlayers) c = c.reshape(xdim*ydim*zdim,order='F') c = numpy.ma.masked_less(c, maskvalue) print("shapes", x.shape, y.shape,z.shape, c.shape) #now we have prepared our data lets plot ax = fig.add_subplot(plotid, projection='3d') sc = ax.scatter(x,y,z,c=c, cmap=plt.hot()) try: plt.colorbar(sc) except: pass
def plotbeam(beamx,beamy,beams,brad,fsuff,plimin=None): from numpy import arange,cos,sin,pi print 'Plotting beams...' print 'WARNING: this can be slow' #plot beams plot.figure(2) plot.clf() plot.hot() titles=array(['PSM Beam','PMW Beam','PLW Beam']) #make circle array tharr=arange(361.)/(2.*pi) xrad=brad*cos(tharr) yrad=brad*sin(tharr) for b in arange(3): print 'plot band %d'%b if b == 2: plot.subplot(2,1,2) else: plot.subplot(2,2,b+1) plot.axis('equal') bplot=log10(beams[:,:,b]) #bplot=where(bplot == -pylab.inf,pylab.NaN,bplot) #replace -inf with NaN #bplot=where(bplot == pylab.inf,pylab.NaN,bplot) #replace inf with NaN #minb=min(bplot[where(bplot > -1.e30 )]) #maxb=max(bplot[where(bplot < 1.e30 )]) #print 'minb,maxb',minb,maxb print 'plimin',plimin if plimin == None: plim=array([-8,0]) else: plim=array([plimin,0]) print 'plim',plim (plim[0],plim[1])=(int(plim[0]),int(plim[1])) #bplot=where(bplot != bplot,plim[0],bplot) #replace NaNs with min #bplot=where(bplot < plim[0],plim[0],bplot) #replace min vals with min #bplot=where(bplot > plim[1],plim[1],bplot) #replace max vals with max prange=plim[1]-plim[0] ntick=8 ncol=32 #tlevs=arange(plim[0],plim[1]+prange/ntick,prange/ntick) clevs=arange(plim[0],plim[1]+prange/ncol,prange/ncol) #print 'Ticks:',tlevs print 'Colours:',clevs plot.contourf(beamx,beamy,bplot,levels=clevs) plot.plot(xrad,yrad,'k:') #plot.plot(xrad,yrad,'w:') plot.clim(plim[0],plim[1]) plot.xlim(min(beamx),max(beamx)) plot.ylim(min(beamy),max(beamy)) plot.title(titles[b]) if b == 0: plot.xticks((floor(min(beamx[:,0])),0,ceil(max(beamx[:,0]))),('','','')) else: plot.xticks((floor(min(beamx[:,0])),0,ceil(max(beamx[:,0])))) plot.xlabel('x ["]') if b == 1: plot.yticks((floor(min(beamy[0,:])),0,ceil(max(beamy[0,:]))),('','',''),rotation=90) else: plot.yticks((floor(min(beamy[0,:])),0,ceil(max(beamy[0,:]))),rotation=90) plot.ylabel('y ["]') cb=plot.colorbar(format='%.1f')#,ticks=tlevs) cb.set_label('Log scale') # print 'plot PMW' # plot.subplot(2,2,2) # plot.axis('equal') # plot.contourf(beamx,beamy,bplot[:,:,1]-max(bplot[:,:,1]),levels=levs) # plot.clim(plim[0],plim[1]) # plot.title('PMW Beam') # plot.xticks((floor(min(beamx[:,0])),0,ceil(max(beamx[:,0])))) # #plot.yticks((floor(min(beamy[0,:])),0,ceil(max(beamy[0,:])))),rotation=90) # plot.yticks((floor(min(beamy[0,:])),0,ceil(max(beamy[0,:]))),('','',''),rotation=90) # cb=plot.colorbar(format='%.1f',ticks=levs) # cb.set_label('Log scale') # plot.xlabel('x ["]') # # print 'plot PLW' # plot.subplot(2,2,3) # plot.axis('equal') # plot.contourf(beamx,beamy,bplot[:,:,2]-max(bplot[:,:,2]),levels=levs) # plot.clim(plim[0],plim[1]) # plot.title('PLW Beam') # plot.xticks((floor((min(beamx[:,0]))),0,ceil(max(beamx[:,0])))) # plot.yticks((floor((min(beamy[0,:]))),0,ceil(max(beamy[0,:]))),rotation=90) # #plot.colorbar() # cb=plot.colorbar(format='%.1f',ticks=levs) # cb.set_label('Log scale') # #colorbar.set_label('Log scale') # plot.xlabel('x ["]') # plot.ylabel('y ["]') plot.savefig('../Outputs/beams'+fsuff+'.png',transparent=False,dpi=300.)
__author__ = 'Newsteinwell' from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np import math from SALib.sample import saltelli from SALib.analyze import sobol from SALib.test_functions import Ishigami import numpy as np problem = { 'num_vars': 3, 'names': ['x1', 'x2', 'x3'], 'bounds': [[-3.14159265359, 3.14159265359], [-3.14159265359, 3.14159265359], [-3.14159265359, 3.14159265359]] } # Generate samples param_values = saltelli.sample(problem, 1000, calc_second_order=True) # Run model (example) Y = Ishigami.evaluate(param_values) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(param_values[:,0], param_values[:,1], param_values[:,2], c=Y, cmap=plt.hot()) plt.show()
#!/usr/bin/python import matplotlib.pyplot as plt import numpy as np import csv import sys from numpy import genfromtxt dataRead = 'input4.csv' csvRead = csv.DictReader(open(dataRead, 'rbU')) """ n = 3 z = np.zeros(n*n).reshape(n,n) count = 0 for line in csvRead: i = int(line['i']) - 1 j = int(line['j']) - 1 z[i][j] = line['Objective'] count = count + 1 print z fig = plt.figure() plt.hot() plt.pcolormesh(z) plt.colorbar() plt.show() #plt.savefig('example.png')
large_d = large_d + [d.T] large_p = large_p + [p.T] large_u = large_u + [u.T] large_v = large_v + [v.T] vtk_name = vtk_name + [vtk] outname = ppath+vtk[0:-6] da = large_d[0] # print large_d for element in large_d[1:]: dat = numpy.hstack((da, element)) da = dat da = numpy.matrix(da) pyplot.imshow(da) pyplot.hot() pyplot.clim(0,5) pyplot.title("d") pyplot.colorbar(orientation = "horizontal") pyplot.savefig(outname +"_d"+".png") pyplot.cla() pyplot.clf() #print large_d
def toImage(image_data): """ @param im_data uint16 array containing intensities from binary files This function converts the intensity data from all files into an image and saves it """ """ Plots the intensity data using matplotlib; faster but high resolution is lost """ # Removes values below a threshold to make the background of the ring images # black image_data.shape = size plt.imshow(np.minimum(stats.threshold(image_data,threshmin=threshold, newval=0), 255 + 0*image_data)) # Specifies the color map; can be modified if you want! plt.hot() # Saves image to output directory plt.savefig(imDirectory + output + "-lo.png") """ Plots the intensity map by converting intensities to RGB values; slower but has higher resolution """ # Determines max intensity for the gradient maxI = np.max(image_data) # creates an mxnx3 array of zeros of type uint8; this array will store # the RGB values that will be converted to an image rgbArr = np.zeros((size[0],size[0],3),dtype = 'uint8') sys.stdout.write("Converting to Image\n") for i in range(size[0]): for j in range(size[0]):
def bind_and_plot(serie1, serie2, color_serie = '', describe = '', return_obj = False, return_ma = False, smooth_avr = None, xlabel = '', ylabel = '', title = ''): '''Scatter plot : enter series (3rd serie for color)''' assert (not return_obj) or (not return_ma) def movingaverage(interval, window_size): window= numpy.ones(int(window_size))/float(window_size) return numpy.convolve(interval, window, 'same') def avr_in_window(x, step , test): selector = test.apply(lambda ligne: x-step/2 <= ligne['x'] and ligne['x']<x+step/2, axis = 1) avr = test.loc[selector, 'y'].mean() return(avr) test = pd.merge(pd.DataFrame(serie1), pd.DataFrame(serie2), left_index = True, right_index = True, how='inner') test.dropna(inplace = True) print str(len(test)) + ' points' if isinstance(color_serie, str): test.columns = ['x', 'y'] test = test.sort('x') test = test[test['y'] != np.inf] plt.scatter(test['x'], test['y'], alpha = 0.1) if smooth_avr != None: y_av = movingaverage(test['y'], smooth_avr) # print y_av # if return_ma: # return([test['x'], y_av]) plt.plot(test['x'], y_av, c = "r") else: test = pd.merge(test, pd.DataFrame(color_serie), left_index = True, right_index = True, how='inner') test.columns = ['x', 'y', 'z'] test = test.sort('x') test = test[test['y'] != np.inf] plt.scatter(test['x'], test['y'], c = test['z'], s=40, lw = 0.1, alpha = 0.1) plt.hot() if smooth_avr != None: y_av = movingaverage(test['y'], smooth_avr) plt.plot(test['x'], y_av,"r") # max_range = test['x'].max() # step = max_range / smooth_avr # x_curve = [step/2 + step * i for i in range(smooth_avr)] # y_curve = [avr_in_window(x, step, test) for x in x_curve] # plt.plot(x_curve, y_curve, "g") # plt.xlabel(xlabel) # plt.ylabel(ylabel) # plt.title(title) # if describe == 'describe': obj = test.groupby('0_x').describe() elif describe == 'mean': obj = test.groupby('0_x').mean() elif describe == 'min_max': obj = [test.groupby('0_x').min(), test.groupby('0_x').max()] elif describe == 'count': obj = test.groupby('0_x').count() if return_ma: plt.show() return if return_obj: plt.show() return obj elif describe != '': print obj plt.show() else: plt.show()