def nice_plot(data,xmin,xmax,xint,centerlat,centerlon,stations,color,cmin, cmax,levels_t): """Make plots in map projection, requires input array, x-min max and interval (also used for y), center of data in lat, lon, station locations, color scale, min and max limits and levels array for color scale. """ domain = xmax-xint/2. maps = Basemap(projection='laea',lat_0=centerlat,lon_0=centerlon, width=domain*2,height=domain*2) s = plt.pcolormesh(np.arange(xmin-xint/2.,xmax+3*xint/2.,xint)+domain, np.arange(xmin-xint/2.,xmax+3*xint/2.,xint)+domain, data, cmap = color) s.set_clim(vmin=cmin,vmax=cmax) CS = plt.contour(np.arange(xmin,xmax+xint,xint)+domain, np.arange(xmin,xmax+xint,xint)+domain, data, colors='k',levels=levels_t) plt.clabel(CS, inline=1, fmt='%1.2f',fontsize=8) plt.scatter(stations[:,0]+domain, stations[:,1]+domain, color='k',s=2) maps.drawstates() fig = plt.gcf() circle=plt.Circle((domain,domain),100000,color='0.5',fill=False) fig.gca().add_artist(circle) circle=plt.Circle((domain,domain),200000,color='0.5',fill=False) fig.gca().add_artist(circle)
def plot_mle_graph(function, mle_params, x_start=eps, x_end=1 - eps, y_start=eps, y_end=1 - eps, resolution=100, x_label="x", y_label="y", show_constraint=False, show_optimum=False): x = np.linspace(x_start, x_end, resolution) y = np.linspace(y_start, y_end, resolution) xx, yy = np.meshgrid(x, y) np_func = np.vectorize(lambda x, y: function(x, y)) z = np_func(xx, yy) optimal_loss = function(*mle_params) levels_before = np.arange(optimal_loss - 3.0, optimal_loss, 0.25) levels_after = np.arange(optimal_loss, min(optimal_loss + 2.0, -0.1), 0.25) fig = plt.figure() contour = plt.contour(x, y, z, levels=np.concatenate([levels_before, levels_after])) plt.xlabel(x_label) plt.ylabel(y_label) if show_constraint: plt.plot(x, 1 - x) if show_optimum: plt.plot(mle_params[0], mle_params[1], 'ro') plt.clabel(contour) return mpld3.display(fig)
def overlayCnvCntrs(self): """Overlay convection contours from mapex data **Belongs to**: :class:`MapConv` **Returns**: contours of convection are overlayed on the map object. **Example**: :: MapConv.overlayCnvCntrs() """ from matplotlib.ticker import LinearLocator import matplotlib.pyplot as plt # get the lats, lons and potentials from calcCnvPots() function ( latCntr, lonCntr, potCntr ) = self.calcCnvPots() #plot the contours xCnt, yCnt = self.mObj( lonCntr, latCntr, coords=self.plotCoords ) cntrPlt = self.mObj.contour( xCnt, yCnt, potCntr, zorder = 2., vmax=potCntr.max(), vmin=potCntr.min(), colors = 'DarkSlateGray', linewidths=1., locator=LinearLocator(12) ) plt.clabel(cntrPlt, inline=1, fontsize=10)
def free_energy(centers, A, levels=None, norm=None,\ fmt='%.1f', method='linear', fill_value=np.nan, ax = None): r"""Make contourplot of alanine-dipeptide free energy. The scattered data is interpolated onto a regular grid before plotting. Parameters ---------- centers : (N, 2) ndarray (phi, psi) coordinates of MSM discretization. A : (N, ) ndarray, Free energy. ax : optional matplotlib axis to plot to """ X, Y=np.meshgrid(xcenters, ycenters) Z=griddata(centers, A, (X, Y), method=method, fill_value=fill_value) Z=Z-Z.min() if levels is None: levels=np.linspace(0.0, 50.0, 10) V=np.asarray(levels) if ax is None: fig=plt.figure() ax=fig.add_subplot(111) ax.set_xlim(-180.0, 180.0) ax.set_ylim(-180.0, 180.0) ax.set_xticks(np.linspace(-180.0, 180.0, 11)) ax.set_yticks(np.linspace(-180.0, 180.0, 11)) ax.set_xlabel(r"$\phi$") ax.set_ylabel(r"$\psi$") cs=ax.contour(X, Y, Z, V, norm=norm) plt.clabel(cs, inline=1, fmt=fmt) plt.grid()
def plot(variables,prev_vars,pltenv): cont_int = 10 cont_smooth = 0.5 thin = 10 lvl = 2 time = 0 x = pltenv['x'] y = pltenv['y'] m = pltenv['map'] bbox = dict(boxstyle="square",ec='None',fc=(1,1,1,0.75)) T= variables['T_PL'][time][lvl] temp = T - 273.15 # convert to Celsius levels = np.arange(-100,150,5) levels2 = np.arange(-50,50,1) P = m.contour(x,y,temp,levels=levels,colors='k') plt.clabel(P,inline=1,fontsize=10,fmt='%1.0f',inline_spacing=1) P = m.contour(x,y,temp,levels=[0],colors='r') plt.clabel(P,inline=1,fontsize=10,fmt='%1.0f',inline_spacing=1) m.contourf(x,y,temp, levels=levels2, extend='both')
def plot_curves(curve1, curve2, size_x, picture_name): """ function eats .dat files """ size_y=size_x shape = [int(size_x),int(size_y)] data_1 = np.loadtxt(curve1) x_1 = data_1[:,0].reshape(shape,order='C') y_1 = data_1[:,1].reshape(shape,order='C') f_1 = data_1[:,2].reshape(shape,order='C') # plt.plot(x_end,rho_end, label='curve 1') a = plt.contour(x_1, y_1, f_1,30, label='curve 1') print np.max(f_1) data_2 = np.loadtxt(curve2) x_2 = data_2[:,0].reshape(shape,order='C') y_2 = data_2[:,1].reshape(shape,order='C') rho_2 = data_2[:,2].reshape(shape,order='C') b = plt.contourf(x_2,y_2,rho_2,30, label='curve 2') # b = plt.contour(xcoords, ycoords, step) print np.max(rho_2) plt.clabel(a, inline=1, fontsize=10) plt.clabel(b, inline=1, fontsize=10) plt.legend() cbar = plt.colorbar(b) # ymax = max(np.max(rho_end1),np.max(rho_end)) # ymin = min(np.min(rho_end),np.min(rho_end1)) # xmax = max(np.max(x_end1),np.max(x_end)) # xmin = min(np.min(x_end),np.min(x_end1)) #print xmax, xmin, ymax, ymin #plt.axis([0,1/6.,0,1]) plt.axes().set_aspect('equal') plt.savefig(str(picture_name)+'.png', dpi=300)
def Pcolor(xs, ys, zs, pcolor=True, contour=False, **options): """Makes a pseudocolor plot. xs: ys: zs: pcolor: boolean, whether to make a pseudocolor plot contour: boolean, whether to make a contour plot options: keyword args passed to pyplot.pcolor and/or pyplot.contour """ Underride(options, linewidth=3, cmap=matplotlib.cm.Blues) X, Y = np.meshgrid(xs, ys) Z = zs x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False) axes = pyplot.gca() axes.xaxis.set_major_formatter(x_formatter) if pcolor: pyplot.pcolormesh(X, Y, Z, **options) if contour: cs = pyplot.contour(X, Y, Z, **options) pyplot.clabel(cs, inline=1, fontsize=10)
def MonotoneRegion(): matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'out' delta = 0.025 w2 = np.arange(-5.0, 5.0, delta) a = np.arange(0.0, 5.0, delta) W2, A = np.meshgrid(w2, a) LAM_cc = -1. + 5.*(A**2.) - np.sqrt(1. + A**4. + 2.*(A**2.)*(-1. + 8.*(W2**2.))) # They're actually the same boundary!!!! # solve for when square root above is less than b^2 and you get same as below, LAM_eg LAM_eg = -1. + 3.*(A**2.) - 2.*(W2**2.) # You can force all the contours to be the same color. plt.figure() CS = plt.contour(W2, A, LAM_cc, 10, colors='k', # negative contours will be dashed by default ) plt.clabel(CS, fontsize=9, inline=1) plt.title('Monotone Region: Crossing the Curl') plt.savefig('monregion_cc.png') plt.close() plt.figure() CS = plt.contour(W2, A, LAM_eg, 10, colors='k', # negative contours will be dashed by default ) plt.clabel(CS, fontsize=9, inline=1) plt.title('Monotone Region: Extragradient') plt.savefig('monregion_eg.png') plt.close()
def plot_fgmax_grid(): fg = fgmax_tools.FGmaxGrid() fg.read_input_data('fgmax_grid1.txt') fg.read_output() #clines_zeta = [0.01] + list(numpy.linspace(0.05,0.3,6)) + [0.5,1.0,10.0] clines_zeta = [0.001] + list(numpy.linspace(0.05,0.25,10)) colors = geoplot.discrete_cmap_1(clines_zeta) plt.figure(1) plt.clf() zeta = numpy.where(fg.B>0, fg.h, fg.h+fg.B) # surface elevation in ocean plt.contourf(fg.X,fg.Y,zeta,clines_zeta,colors=colors) plt.colorbar() plt.contour(fg.X,fg.Y,fg.B,[0.],colors='k') # coastline # plot arrival time contours and label: arrival_t = fg.arrival_time/3600. # arrival time in hours #clines_t = numpy.linspace(0,8,17) # hours clines_t = numpy.linspace(0,2,5) # hours #clines_t_label = clines_t[::2] # which ones to label clines_t_label = clines_t[::1] # which ones to label clines_t_colors = ([.5,.5,.5],) con_t = plt.contour(fg.X,fg.Y,arrival_t, clines_t,colors=clines_t_colors) plt.clabel(con_t, clines_t_label) # fix axes: plt.ticklabel_format(format='plain',useOffset=False) plt.xticks(rotation=20) plt.gca().set_aspect(1./numpy.cos(fg.Y.mean()*numpy.pi/180.)) plt.title("Maximum amplitude / arrival times (hrs)")
def PlotContour(data_list, ax, args): """ Plot two dimensional density contour. Args: data_list: a list of Data objects ax: a matplotlib axis object args: an argparse arguments object """ if len(data_list) > 1: raise BadInput('You cannot create a contour plot with more ' 'than one input file') data = data_list[0] x = data.x y = data.y H, xedges, yedges = numpy.histogram2d( x, y, range=[[min(x), max(x)], [min(y), max(y)]], bins=(args.contour_bin, args.contour_bin)) extent = [yedges[0], yedges[-1], xedges[0], xedges[-1]] c_max = max(map(max, H)) c_min = min(map(min, H)) nc_levels = args.contour_num_levels if args.contour_logspace: c_levels = numpy.logspace(c_min, c_max, nc_levels) else: c_levels = numpy.linspace(c_min, c_max, nc_levels) im = plt.imshow(H, interpolation='bilinear', origin='lower', cmap=matplotlib.cm.binary, extent=extent) c_set = plt.contour(H, extent=extent, origin='lower', levels=c_levels, colors=ColorPicker(0, args)) plt.clabel(c_set, colors='red', inline=True, fmt='%1.0i', rightside_up=True)
def drawContour(img): contour_image = plt.contour(img, 5) plt.clabel(contour_image, inline=1, fontsize=10) plt.show() return contour_image
def kden_plot(X,Y, im, support, pvals=(.1,.333,.5,.666,.9), contours=True, imshow=True, cbar=False, psupport=True,oned=True, fignum=None,cfontsize=10): if fignum is None: fignum=plt.gcf().number plt.clf() dx=np.abs(X[0,0]-X[1,0]) dy=np.abs(Y[0,0]-Y[0,1]) dxdy=dx*dy if contours: levelsdict={x:'{:3.0f}%'.format(p*100) for x,p in find_prob_contours(im,dxdy,pvals=pvals)} cplt=plt.contour(X,Y,im,colors='k', levels=levelsdict.keys()) plt.clabel(cplt, inline=1, fontsize=10, use_clabeltext=True, fmt=levelsdict) if imshow: plt.imshow(np.rot90(im),aspect='auto', extent=[X.min(), X.max(), Y.min(), Y.max()], cmap=plt.cm.gist_earth_r) if cbar: plt.colorbar() if psupport: plt.plot(support[0],support[1],'r,') if oned: plt.figure(fignum+1) plt.plot(X[:,0],((im*dy).sum(1)))
def test(self): xlim=[-2.0,2.0] ylim=[-2.0,2.0] resol = 0.025 sample_x = np.arange(-2.0,2.0,resol) sample_y = np.arange(-2.0,2.0,resol) sample_X, sample_Y = np.meshgrid(sample_x, sample_y) sample_XX = np.hstack([sample_X.reshape(sample_X.size,1),sample_Y.reshape(sample_Y.size,1)]) sample_Z1 = np.exp(self.gmm_0.score(sample_XX)) sample_Z2 = np.exp(self.gmm_1.score(sample_XX)) plt.figure() ax1 = plt.subplot(121, aspect='equal') CS = plt.contour(sample_X, sample_Y, sample_Z1.reshape(sample_X.shape)) plt.clabel(CS, inline=1, fontsize=10) ax2 = plt.subplot(122, aspect='equal') CS = plt.contour(sample_X, sample_Y, sample_Z2.reshape(sample_X.shape)) plt.clabel(CS, inline=1, fontsize=10) ax1.set_xlim(xlim) ax1.set_ylim(ylim) ax2.set_xlim(xlim) ax2.set_ylim(ylim) plt.show() #print gmm_1.get_params(deep=True) print self.gmm_0.weights_ print self.gmm_0.means_ print self.gmm_0.covars_
def publish(self): alldata = [] for i,val in enumerate(self.status['runs']): print val alldata.append(post_bout.read(path=val)) alldata = np.array(alldata) print "alldata.shape: ", alldata.shape print alldata[0]['Ni']['ave']['amp'].shape data = alldata[0]['Ni']['ave']['amp'] #Nt long array pp = PdfPages('output.pdf') plt.figure() cs = plt.plot(data) plt.title('amplitude ') plt.savefig(pp, format='pdf') gamma = alldata[2]['Ni']['modes'][0]['gamma'] #single value phase = alldata[2]['Ni']['modes'][0]['phase'] #Nt x Nx array plt.figure() cs = plt.contour(phase) plt.clabel(cs, inline=1, fontsize=10) plt.title('phase') plt.savefig(pp, format='pdf') plt.close() pp.close() explain = alldata[0]['meta'] print explain allpickle = open('allpickled.pkl','wb') pickle.dump(alldata,allpickle) allpickle.close()
def animation_plot(i, pressure, wind, direction, step=24): """ Function to update the animation frame. """ # Clear figure to refresh colorbar plt.gcf().clf() ax = plt.axes(projection=ccrs.Mercator()) ax.set_extent([-10.5, 3.8, 48.3, 60.5], crs=ccrs.Geodetic()) contour_wind = iplt.contourf(wind[i][::10, ::10], cmap='YlGnBu', levels=range(0, 31, 5)) contour_press = iplt.contour(pressure[i][::10, ::10], colors='white', linewidth=1.25, levels=range(938, 1064, 4)) plt.clabel(contour_press, inline=1, fontsize=14, fmt='%i', colors='white') quiver_plot(wind[i], direction[i], step) plt.gca().coastlines(resolution='50m') time_points = pressure[i].coord('time').points time = str(pressure[i].coord('time').units.num2date(time_points)[0]) plt.gca().set_title(time) colorbar = plt.colorbar(contour_wind) colorbar.ax.set_ylabel('Wind speed ({})'.format(str(wind[i].units)))
def add_sub_plot(sub_num): plt.subplot(1,1,1) rbf = scipy.interpolate.Rbf(x, y, z, function='linear') zi = rbf(xi, yi) #io parameter interpolation rbf2 = scipy.interpolate.Rbf(xio, yio, zio, function='linear') zion = rbf2(xion, yion) #our contours. Teal for .2 dex and black for 1 dex contour = plt.contour(xi,yi,zi, levels, colors='r', linestyles = 'dashed') contour2 = plt.contour(xi,yi,zi, levels2, colors='k', linewidths=1.5) contour3 = plt.contour(xion,yion, zion, levelsio, colors='c', linewidths = 3) plt.clabel(contour2, inline=1, fontsize=10, fmt='%1.1f') plt.clabel(contour3, inline=1, fontsize=10, fmt='%1.1f') #print the max values right on the plots #plt.scatter(max_values[0,2], max_values[0,3], c ='k',marker = '*', s = 1000) #plt.annotate(max_values[0,0], xy= (max_values[0,2], max_values[0,3]), xytext = (5, -30), textcoords = 'offset points', ha = 'left', va = 'bottom', fontsize=15) #axis limits yt_min = 8 yt_max = 17 xt_min = 0 xt_max = 6 plt.ylim(yt_min,yt_max) plt.xlim(xt_min,xt_max) plt.yticks(arange(yt_min,yt_max+1,1),fontsize=16) plt.xticks(arange(xt_min,xt_max+1,1), fontsize = 16) plt.ylabel('Log ($ \phi _{\mathrm{H}} $)', fontsize=18) plt.xlabel('Log($n _{\mathrm{H}} $)', fontsize=18)
def __make_result_sps(session): sdf_extension = session['SPS'] # if isinstance(sdf_extension, SDFExtension) == False: # return sdf_extension scales = sdf_extension.actual_scales zs = sdf_extension.result_datasets x, y = numpy.meshgrid(scales[1].data, scales[0].data) response_string = '' for zds in zs: if zds.name != 'summary.batteryPower' and zds.name != 'summarySystemSPS.mechanicalPower': continue print zds.data z = numpy.fabs(zds.data) fig = plt.contourf(x, y, z, 10, alpha=.75, cmap=cm.coolwarm) C = plt.contour(x, y, z, 10, colors='black', linewidth=.5) plt.clabel(C, inline=1, fontsize=10) # TODO: Unit hackcode plt.xlabel(scales[1].name + ' (' + str(scales[1].unit) + ')') plt.ylabel(scales[0].name + ' (' + str(scales[0].unit) + ')') plt.title(zds.name) plt.colorbar(fig, shrink=0.5, aspect=5) plt.savefig('temp.svg') with open('temp.svg', 'rb') as f: data = f.read().encode('base64') os.remove('temp.svg') response_string += '<img src="data:image/svg+xml;base64,{0}"><br/>'.format(data) plt.close('all') return response_string
def visCostFun(self,thetaHis): fig = plt.figure() ax = fig.gca(projection='3d') theta0Rg=np.arange(-10, 10, 0.1) theta1Rg=np.arange(-1.,4., 0.01) valJ=np.zeros((len(theta0Rg),len(theta1Rg))) theta0Grid, theta1Grid=np.meshgrid(theta0Rg,theta1Rg) theta=np.zeros(2) for i in range(len(theta0Rg)): for j in range(len(theta1Rg)): theta[0]=theta0Rg[i] theta[1]=theta1Rg[j] valJ[i,j]=1./(2.*self.m)*np.sum(((theta.dot(self.newX.T))-self.y)**2) i,j = np.unravel_index(valJ.argmin(), valJ.shape) # surf = ax.plot_surface(theta0Grid, theta1Grid, valJ.T, rstride=1, cstride=1, cmap=cm.coolwarm, # linewidth=0, antialiased=False) surf = ax.plot_surface(theta0Grid, theta1Grid, valJ.T) plt.xlabel("theta0") plt.ylabel("theta1") plt.show() levels = np.arange(-30.,30.,5) CS=plt.contour(theta0Grid, theta1Grid, valJ.T, levels) plt.clabel(CS, inline=1, fontsize=10) plt.plot([theta0Rg[i]],[theta1Rg[j]],'-ro') for ele in thetaHis: plt.plot([ele[0]],[ele[1]],'b*') plt.xlabel("theta0") plt.ylabel("theta1") plt.show()
def plot_contour(self): if self.fdim == 2: p = [self.x_range.min(), self.x_range.max(), self.y_range.max(), self.y_range.min()] p2 = [self.x_range.min(), self.x_range.max(), self.y_range.min(), self.y_range.max()] plt.imshow(self.z_val, vmin=self.z_val.min(), vmax=self.z_val.max(), extent=p) CS = plt.contour(self.x_range, self.y_range, self.z_val, 15, colors='k') plt.clabel(CS, inline=1, fontsize=10) x_ = [] y_ = [] for i in self.vec: x_.append(i[0]) y_.append(i[1]) plt.plot(x_, y_, color='k') plt.ylabel("x2") plt.xlabel("x1") if self.y_range.max() > 0: plt.ylim(self.y_range.min(), self.y_range.max()) else: plt.ylim(self.y_range.max(), self.y_range.min()) if self.x_range.max() > 0: plt.xlim(self.x_range.min(), self.x_range.max()) else: plt.xlim(self.x_range.max(), self.x_range.min()) plt.show() else: print('Dimension not equal 2')
def plot_image(file_in, num=0, xlab='', ylab='', map_range=[0, 0, 0, 0], color_loc=False, cm='', fig_title='', cont=''): """ plot a given 2d image """ from matplotlib.pyplot import imshow, colorbar, figure from matplotlib.pyplot import xlabel, ylabel from matplotlib.pyplot import title, contour, clabel figure(num) if fig_title != '': title(fig_title) if xlab != '': xlabel(xlab) if ylab != '': ylabel(ylab) if all([v == 0 for v in map_range]): map_range = [0, len(file_in), 0, len(file_in)] if cm == '': imshow(file_in, extent=map_range, origin='lower', interpolation='None') else: imshow(file_in, extent=map_range, origin='lower', interpolation='None', cmap=cm) if color_loc: colorbar() if cont != '': CS = contour(file_in, cont, extent=map_range, origin='lower', hold='on', colors=('k', )) clabel(CS, inline=1, fmt='%2.1f', fontsize=10)
def epsPlot(subplot, filename, text): scale,S,count, members = pickle.load(open(filename,'rb')) #plt.subplot(2,3,i,adjustable='box', aspect=5) ax = plt.subplot(2,3,subplot) levels = [] if subplot <=3: levels = np.linspace(0, 3, 13) else: levels = np.linspace(0, 8, 33) print levels CS = plt.contourf(S,levels = levels,extent = (EPSRANGE[0],EPSRANGE[-1],NMINRANGE[0], NMINRANGE[-1]),aspect='auto') plt.text(.08,3.5 ,text) plt.setp(ax.get_xticklabels(), rotation='vertical', fontsize=12) CS2 = plt.contour(count,[1,2,3,4,5,6],extent = (EPSRANGE[0],EPSRANGE[-1],NMINRANGE[0], NMINRANGE[-1]),colors = 'k') plt.clabel(CS2, inline=1, fontsize=12, colors = 'k') plt.ylabel(r'$N_{min}$') plt.xlabel(r'$\epsilon$') #if (subplot == 3 or subplot == 6): if ( subplot == 6): cax = fig2.add_axes([0.91, 0.1, 0.03, 0.365]) cbar = plt.colorbar(CS , cax=cax) cbar.ax.set_ylabel('S') if ( subplot == 3): cax = fig2.add_axes([0.91, 0.535, 0.03, 0.365]) cbar = plt.colorbar(CS , cax=cax) cbar.ax.set_ylabel('S') return
def plot_TS(temp, psal, depth, lon, lat, svec, tvec, density, title, m, figname): ''' Create the T-S diagram ''' logger = logging.getLogger(__name__) fig = plt.figure(figsize=(15, 15)) rcParams.update({'font.size': 18}) plt.scatter(psal, temp, s=5, c=depth, vmin=10., vmax=1000., edgecolor='None', cmap=plt.cm.plasma) cbar = plt.colorbar(extend='max') plt.xlabel('Salinity', fontsize=18) plt.ylabel('Temperature\n($^{\circ}$C)', rotation=0, ha='right', fontsize=18) cont = plt.contour(svec, tvec, density, levels=np.arange(22., 32., 1.), colors='.65', linestyles='dashed', lineswidth=0.5) plt.clabel(cont,inline=True, fmt='%1.1f') plt.xlim(smin, smax) plt.ylim(tmin, tmax) cbar.set_label('Depth\n(m)', rotation=0, ha='left') plt.grid(color="0.6") # Add an inset showing the positions of the platform inset=plt.axes([0.135, 0.625, 0.3, 0.35]) lon2plot, lat2plot = m(lon, lat) m.drawmapboundary(color='w') m.plot(lon2plot, lat2plot, 'ro', ms=2, markeredgecolor='r') #m.drawcoastlines(linewidth=0.25) m.drawlsmask(land_color='0.4', ocean_color='0.9', lakes=False) plt.title(title, fontsize=20) plt.savefig(figname, dpi=150) # plt.show() plt.close()
def contour(x,y,z, linewidth = 2, labels = None): """ Plots contours for non-evenly spaced data. x,y,z must be 1d arrays. lines = # of contour lines (default 18 ) linewidth = line width of lines (default 2 ) """ assert x.shape[0] == y.shape[0] == z.shape[0], "arrays x,y,z must be the same size" #make a grid that surrounds x,y support xi = np.linspace(x.min(),x.max(),100) yi = np.linspace(y.min(),y.max(),100) # grid the data. zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic') # contour the gridded data, plotting dots at the randomly spaced data points. plt.figure() CS = plt.contour(xi,yi,zi,linewidth=2) plt.clabel(CS, inline=1, fontsize=10) if labels: plt.xlabel(labels[0]) plt.ylabel(labels[1]) # plot data points. plt.scatter(x,y,c=z,s=60, alpha = 0.7, edgecolors = "none") plt.xlim(x.min(),x.max()) plt.ylim(y.min(),y.max()) plt.show()
def main(): # Lets relax a 1D array of values. N = 20 a = 0.0 b = 1.0 u = np.zeros(20) u[0] = a u[-1] = b x = np.arange(0.0, float(len(u)), 1.0) / float(len(u) - 1) u = relax1D(u) print "It took %d iterations to reach the desired tolerance." % (len(u) - 1) animate1Dframes(x, u) plt.plot(x, u[-1], "-sk") plt.savefig("Relaxed1D.png") plt.close() # Now lets relax a 2D array of values. Such that the top and bottom edges are set to zero # and the left and right edges are set to one. u2D = np.zeros((N, N)) u2D[0,:] = a u2D[-1,:] = a u2D[:,0] = b u2D[:,-1] = b u2D = relax2D(u2D) print "It took %d iterations to reach the desired tolerance." % (len(u2D) - 1) animate2Dframes(u2D) u2D_cf = plt.contour(u2D[-1], levels=np.arange(0, 1, 0.1)) plt.clabel(u2D_cf, colors='k') plt.savefig("Relaxed2D.png") plt.close()
def plot_pressuremap(data, title='pressure pattern', sub_title='ploted in birdhouse'): """ plots pressure data :param data: 2D or 3D array of pressure data. if data == 3D a mean will be calculated :param title: string for title :param sub_title: string for sub_title """ from numpy import squeeze, mean d = squeeze(data) if len(d.shape)==3: d = mean(d, axis=0) if len(d.shape)!=2: logger.error('data are not in shape for map display') co = plt.contour(d, lw=2, c='black') cf = plt.contourf(d) plt.colorbar(cf) plt.clabel(co, inline=1) # fontsize=10 plt.title(title) plt.annotate(sub_title, (0,0), (0, -30), xycoords='axes fraction', textcoords='offset points', va='top') ip, image = mkstemp(dir='.',suffix='.png') plt.savefig(image) plt.close() return image
def main(): dir='/Users/ph290/Public/mo_data/ostia/' # on ELD140 filename = dir + '*.nc' cube = iris.load_cube(filename,'sea_surface_temperature',callback=my_callback) #reads in data using a special callback, because it is a nasty netcdf file cube.data=cube.data-273.15 sst_mean = cube.collapsed('time', iris.analysis.MEAN) #average all 12 months together sst_stdev=cube.collapsed('time', iris.analysis.STD_DEV) caribbean = iris.Constraint( longitude=lambda v: 260 <= v <= 320, latitude=lambda v: 0 <= v <= 40, name='sea_surface_temperature' ) caribbean_sst_mean = sst_mean.extract(caribbean) caribbean_sst_stdev = sst_stdev.extract(caribbean) #extract the Caribbean region fig = plt.figure() ax = plt.axes(projection=ccrs.PlateCarree()) data=caribbean_sst_mean.data data2=caribbean_sst_stdev.data lons = caribbean_sst_mean.coord('longitude').points lats = caribbean_sst_mean.coord('latitude').points lo = np.floor(data.min()) hi = np.ceil(data.max()) levels = np.linspace(lo,hi,100) lo2 = np.floor(data2.min()) hi2 = np.ceil(data2.max()) levels2 = np.linspace(lo2,5,10) cube_label = 'latitude: %s' % caribbean_sst_mean.coord('latitude').points contour=plt.contourf(lons, lats, data,transform=ccrs.PlateCarree(),levels=levels,xlabel=cube_label) #filled contour the annually averaged temperature contour2=plt.contour(lons, lats, data2,transform=ccrs.PlateCarree(),levels=levels2,colors='k') #contour the standard deviations plt.clabel(contour2, inline=0.5, fontsize=12,fmt='%1.1f' ) ax.add_feature(cartopy.feature.LAND) ax.coastlines() ax.add_feature(cartopy.feature.RIVERS) ax.add_feature(cartopy.feature.BORDERS, linestyle=':') #ax.add_feature(cartopy.feature.LAKES, alpha=0.5) cbar = plt.colorbar(contour, ticks=np.linspace(lo,hi,7), orientation='horizontal') cbar.set_label('Sea Surface Temperature ($^\circ$C)') # enable axis ticks ax.xaxis.set_visible(True) ax.yaxis.set_visible(True) # fix 10-degree increments and don't clip range plt.locator_params(steps=(1,10), tight=False) # add gridlines plt.grid(True) # add axis labels plt.xlabel('longitude') plt.ylabel('latitude') #plt.show() plt.savefig('/home/h04/hador/public_html/twiki_figures/carib_sst_and_stdev.png')
def plot_area(dataset, request, area_prediction): bot_lat, top_lat, left_lon, right_lon = request['predict_area'] plt.figure(figsize=(20, 15)) # Plot stations sp = plt.scatter( dataset.longitude, dataset.latitude, s=10, c=dataset['TT2m_error'], edgecolor='face', vmin=-5, vmax=5, ) # Contours contour_handle = plt.contour( area_prediction, np.arange(-5, 5, 1), antialiased=True, extent=(left_lon, right_lon, top_lat, bot_lat), zorder=999, alpha=0.5 ) plt.clabel(contour_handle, fontsize=11) # Color bar cb = plt.colorbar(sp) cb.set_label('Temperature error') plt.show()
def draw(self): filename = self.filename file = open(os.getcwd() + "\\" + filename, 'r') lines = csv.reader(file) # data = [] x = [] y = [] z = [] for line in lines: try: data.append(line) except Exception as e: print e pass # print data for i in range(1, len(data)): try: x.append(float(data[i][0])) y.append(float(data[i][1])) z.append(float(data[i][3])) finally: pass xx = np.array(x) yy = np.array(y) zz = np.array(z) # print np.min(xx) tx = np.linspace(np.min(xx), np.max(xx), 100) ty = np.linspace(np.min(yy), np.max(yy), 100) XI, YI = np.meshgrid(tx, ty) rbf = interpolate.Rbf(xx, yy, zz, epsilon=2) ZI = rbf(XI, YI) # plt.gca().set_aspect(1.0) font = font_manager.FontProperties(family='times new roman', style='italic', size=16) cs = plt.contour(XI, YI, ZI, colors="black") plt.clabel(cs, cs.levels, inline=True, fontsize=10, prop=font) plt.subplot(1, 1, 1) plt.pcolor(XI, YI, ZI, cmap=cm.jet) plt.scatter(xx, yy, 100, zz, cmap=cm.jet) plt.title('interpolation example') plt.xlim(int(xx.min()), int(xx.max())) plt.ylim(int(yy.min()), int(yy.max())) plt.colorbar() plt.savefig("interpolation.jpg") #plt.show() return ZI, XI, YI
def eigenvector(centers, ev, levels=None, norm=None,\ fmt='%.e', method='linear', fill_value=np.nan): r"""Make contourplot of alanine-dipeptide stationary distribution The scattered data is interpolated onto a regular grid before plotting. Parameters ---------- centers : (N, 2) ndarray (phi, psi) coordinates of MSM discretization. ev : (N, ) ndarray, Right eigenvector """ X, Y=np.meshgrid(xcenters, ycenters) Z=griddata(centers, ev, (X, Y), method=method, fill_value=fill_value) if levels is None: levels=np.linspace(-0.1, 0.1, 21) V=np.asarray(levels) fig=plt.figure() ax=fig.add_subplot(111) ax.set_xlim(-180.0, 180.0) ax.set_ylim(-180.0, 180.0) ax.set_xticks(np.linspace(-180.0, 180.0, 11)) ax.set_yticks(np.linspace(-180.0, 180.0, 11)) ax.set_xlabel(r"$\phi$") ax.set_ylabel(r"$\psi$") cs=ax.contour(X, Y, Z, V, norm=norm) plt.clabel(cs, inline=1, fmt=fmt) plt.grid()
def plotSNR(R, snr, T0, fname = '/Users/jmrv/Desktop/snr.pdf'): pp = PP(fname) plt.clf() T = T0*10**(np.arange(-2, 1.5, 0.1)) scale = np.sqrt(T/T0) snrGrid = np.zeros((len(R), len(T))) for i in range(len(snr)): snrGrid[i,:] = scale*snr[i] levels = np.array([0.5, 1, 2, 3, 5, 10, 15, 20])/10 c = plt.contour(T/1e3, R*1000, snrGrid, levels, colors='k') plt.clabel(c, fontsize=9, inline=1) plt.xscale('log') plt.yscale('log') plt.title('Signal-to-noise of Sc signal in the X-ray band') plt.ylabel('Instrument resolution (eV, FWHM)') plt.xlabel('Exposure (ks)') #plt.ticklabel_format(style='plain', axis='both') pp.savefig() pp.close() print '\nplotted '+fname
f(points[i][0], points[i][1]), marker='o', color="red") # Plot the point ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') ax2 = fig.add_subplot(2, 2, 2) ax2.set_title('Contour Map') cp = plt.contour(X, Y, f(X, Y), colors='black', linestyles='dashed', linewidths=1) # Plot the line map plt.clabel(cp, inline=1, fontsize=10) cp = plt.contourf(X, Y, f(X, Y), 50, cmap='viridis') # Plot the contour map ax2.plot(points[i][0], points[i][1], marker='o', color="red") # Plot the point ax2.set_xlabel('x') ax2.set_ylabel('y') ax3 = fig.add_subplot(2, 2, 3) ax3.set_title('Convergence') ax3.grid() ax3.plot(list(range(0, i + 1)), convergence) ax4 = fig.add_subplot(2, 2, 4, frameon=False) ax4.table(colLabels=['Iteration', 'Current Min', 'Convergence'], cellText=[[
#Z2 = np.array([[p2n(p, q) for p in pp] for q in qq]) #Z4 = np.array([[p4n(p, q) for p in pp] for q in qq]) Z6 = np.array([[p6n2(p, q) for p in pp] for q in qq]) save_memoized(p6n2, 'fp6n2') #Z8 = np.array([[p8(p, q) for p in pp] for q in qq]) bare_qubit = PP #from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) fontsize=16 Z = Z6 - (1 - PP)**2 cont = ax.contour(QQ, PP, Z, [0.06, 0.05, 0.04, 0.03, 0.02, 0.01], colors = ('black')) plt.clabel(cont, inline=1, fontsize=fontsize) cont2 = ax.contour(QQ, PP, Z, [0], colors = ('black'), linewidths=(3)) plt.clabel(cont2, inline=1, fontsize=fontsize) plt.xlabel('$q$', fontsize=fontsize) plt.ylabel('$p$', fontsize=fontsize) plt.show() plt.savefig('full_lying.pdf', format='pdf') plt.savefig('../writeup/assets/full_lying.pdf', format='pdf')
def f(x, y): return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 - y**2) n = 256 x = np.linspace(-3, 3, n) y = np.linspace(-3, 3, n) # 将线和值进行绑定 X, Y = np.meshgrid(x, y) # cmap是color map可以根据值在颜色图中找到对应的颜色 # 使用plt.contourf去填充contour(轮廓) plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot) # 添加的是轮廓线 C = plt.contour(X, Y, f(X, Y), 8, colors='black') # 在线上添加数字 plt.clabel(C, inline=True, fontsize=10.5) plt.xticks(()) plt.yticks(()) # 传入图片 plt.figure(num=7) # 用像素点模拟图片 a = np.array([ 0.31513153135, 0.1564651254, 0.51678534535, 0.15646765444, 0.1646524525, 0.45534545345, 0.48641513213, 0.15646557613, 0.6649879843 ]).reshape(3, 3) # interpolation的参考地址是http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower') plt.xticks([]) plt.yticks([])
x_new.sort() y_new.sort() Prob = np.zeros([len(x_new), len(y_new)]) for i in xrange(len(x_new)): for j in xrange(len(y_new)): if (x_new[i], y_new[j]) in f: Prob[i, j] = f[(x_new[i], y_new[j])] level = np.arange(0.00, 0.9, 0.05) plt.figure(1) G1 = plt.contour(x_new, y_new, Prob.transpose(), levels=level) plt.clabel(G1, inline=1, fontsize=10) plt.xlabel('Gluino mass (GeV)') plt.ylabel('Neutralino mass (GeV)') plt.title('037 (d) GttN1') plt.axis([750, 1800, 150, 1600]) plt.grid(True) plt.show() q = open('037_d.txt', 'w') Pt = Prob.transpose() for i in xrange(len(x_new)): for j in xrange(len(y_new)): q.write( str(x_new[i]) + ' ' + str(y_new[j]) + ' ' + str(Pt[i, j]) + ' \n')
def main(myfiles, fieldname, fieldlevel, idm=None, jdm=None, clim=None, filetype="archive", window=None, cmap="jet", datetime1=None, datetime2=None, vector="", tokml=False, exptid="", masklim=None, dpi=180): cmap = plt.get_cmap("jet") LinDic = mod_hyc2plot.cmap_dict('sawtooth_fc100.txt') my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap', LinDic) cmap = my_cmap if vector: cmap = cmocean.cm.speed if tokml: ab = abf.ABFileGrid("regional.grid", "r") plon = ab.read_field("plon") plat = ab.read_field("plat") ab.close() ab = abf.ABFileGrid("regional.grid", "r") plon = ab.read_field("plon") plat = ab.read_field("plat") ab.close() proj = ccrs.Stereographic(central_latitude=90.0, central_longitude=-40.0) pxy = proj.transform_points(ccrs.PlateCarree(), plon, plat) px = pxy[:, :, 0] py = pxy[:, :, 1] x, y = np.meshgrid(np.arange(plon.shape[1]), np.arange(plon.shape[0])) if vector: logger.info("Vector component 1:%s" % fieldname) logger.info("Vector component 2:%s" % vector) figure = plt.figure(figsize=(8, 8)) ax = figure.add_subplot(111) ax.set_facecolor('xkcd:gray') onemm = 9.806 counter = 0 sum_fld = np.zeros(plon.shape) sumf1 = np.zeros(plon.shape) sumf2 = np.zeros(plon.shape) file_count = 0 for myfile0 in myfiles: # Open files, and return some useful stuff. # ab2 i used in case of vector # rdtimes is used for plotting forcing fields n_intloop, ab, ab2, rdtimes = open_file(myfile0, filetype, fieldname, fieldlevel, datetime1=datetime1, datetime2=datetime2, vector=vector, idm=idm, jdm=jdm) # Intloop used to read more fields in one file. Only for forcing for now for i_intloop in range(n_intloop): # Read ab file of different types if filetype == "archive": fld1 = ab.read_field(fieldname, fieldlevel) if vector: fld2 = ab.read_field(vector, fieldlevel) elif filetype == "regional.depth": fld1 = ab.read_field(fieldname) elif filetype == "forcing": fld1 = ab.read_field(fieldname, rdtimes[i_intloop]) if vector: fld2 = ab2.read_field(vector, rdtimes[i_intloop]) logger.info("Processing time %.2f" % rdtimes[i_intloop]) else: raise NotImplementedError("Filetype %s not implemented" % filetype) if not window: J, I = np.meshgrid(np.arange(fld1.shape[0]), np.arange(fld1.shape[1])) else: J, I = np.meshgrid(np.arange(window[1], window[3]), np.arange(window[0], window[2])) print('mnfld1,mxfld1=', fld1.min(), fld1.max()) # Create scalar field for vectors if vector: fld = np.sqrt(fld1**2 + fld2**2) print('mnfld2,mxfld2=', fld2.min(), fld2.max()) else: fld = fld1 # Apply mask if requested if masklim: fld = np.ma.masked_where(fld <= masklim[0], fld) fld = np.ma.masked_where(fld >= masklim[1], fld) sum_fld = sum_fld + fld counter = counter + 1 if vector: sumf1 = sumf1 + fld1 sumf2 = sumf2 + fld2 file_count = file_count + 1 # End i_intloop print('Computing the avearge of file_counter= ', file_count, 'counter=', counter) if file_count > 0: fld_Avg = sum_fld / file_count print('mn_Avg_fld,mx_Avg_fld=', fld_Avg.min(), fld_Avg.max()) if vector: f1_avg = sumf1 / file_count f2_avg = sumf2 / file_count print('mn_avg_fld1,mx_avg_fld1=', f1_avg.min(), f1_avg.max()) print('mn_avg_fld2,mx_avg_fld2=', f2_avg.min(), f2_avg.max()) if fieldname == 'k.e.': P = plt.pcolormesh(x[J, I], y[J, I], np.log10(fld_Avg[J, I]), cmap=cmap, shading='auto') elif fieldname == 'srfhgt': P = plt.pcolormesh(x[J, I], y[J, I], (fld_Avg[J, I] / onemm), cmap=cmap, shading='auto') else: P = plt.pcolormesh(x[J, I], y[J, I], fld_Avg[J, I], cmap=cmap, shading='auto') if 'temp' in fieldname: P1=plt.contour(x[J,I],y[J,I],fld_Avg[J,I],levels=[-1.,1,4.0,8], \ colors=('w',),linestyles=('-',),linewidths=(1.5,)) plt.clabel(P1, fmt='%2.1d', colors='w', fontsize=10) #contour line labels if vector: skip = 10 logger.info("ploting quiver .......>>> %s" % vector) I2 = I[::skip, ::skip] J2 = J[::skip, ::skip] plt.quiver(x[J2, I2], y[J2, I2], f1_avg[J2, I2], f2_avg[J2, I2]) ## # Print figure and remove wite space. ax.set_facecolor('xkcd:gray') aspect = 40 pad_fraction = 0.25 divider = make_axes_locatable(ax) width = axes_size.AxesY(ax, aspect=1. / aspect) pad = axes_size.Fraction(pad_fraction, width) cax = divider.append_axes("right", size=width, pad=pad) if vector: cb = ax.figure.colorbar(P, cax=cax, extend='max') else: cb = ax.figure.colorbar(P, cax=cax, extend='both') if clim is not None: P.set_clim(clim) ax.set_title('Avg' + "%s:%s(%d)" % (myfile0, fieldname, fieldlevel)) # Print figure. fnamepng_template = exptid + "Avg_%s_%d_%03d_Avg.png" fnamepng = fnamepng_template % (fieldname, fieldlevel, counter) logger.info("output in %s" % fnamepng) figure.canvas.print_figure(fnamepng, bbox_inches='tight', dpi=dpi) ax.clear() cb.remove()
grad[0] = 400 * y[0] * (y[0]**2 - y[1]) + 2 * (y[0] - 1) grad[1] = 200 * (y[1] - y[0]**2) return grad ##Q1 xmin, xmax, ymin, ymax = -1.5, 1.5, -0.5, 1.5 xx = np.linspace(xmin, xmax, 500) yy = np.linspace(ymin, ymax, 500) [X, Y] = np.meshgrid(xx, yy) fXY = rosenbrock([X, Y]) plt.figure(1) plt.clf() CS = plt.contour(X, Y, fXY, np.logspace(-0.5, 3.5, 20, base=10)) plt.clabel(CS, inline=1, fontsize=10) plt.title('Lignes de niveau de Rosenbrock') plt.show() ##Q2 epsilon = 10**-8 def GPF(h, x0, f_grad, epsilon=10**-8, n_max=1000): error = 1 increment = 0 XX = [x0] while error > epsilon and increment < n_max: x1 = x0 - h * f_grad(x0) error = np.linalg.norm(x0 - x1, 2) x0 = x1 increment += 1
def plot_fisher_information_contours_2d( fisher_information_matrices, fisher_information_covariances=None, reference_thetas=None, contour_distance=1.0, xlabel=r"$\theta_0$", ylabel=r"$\theta_1$", xrange=(-1.0, 1.0), yrange=(-1.0, 1.0), labels=None, inline_labels=None, resolution=500, colors=None, linestyles=None, linewidths=1.5, alphas=1.0, alphas_uncertainties=0.25, ): """ Visualizes 2x2 Fisher information matrices as contours of constant Fisher distance from a reference point `theta0`. The local (tangent-space) approximation is used: distances `d(theta)` are given by `d(theta)^2 = (theta - theta0)_i I_ij (theta - theta0)_j`, summing over `i` and `j`. Parameters ---------- fisher_information_matrices : list of ndarray Fisher information matrices, each with shape (2,2). fisher_information_covariances : None or list of (ndarray or None), optional Covariance matrices for the Fisher information matrices. Has to have the same length as fisher_information_matrices, and each entry has to be None (no uncertainty) or a tensor with shape (2,2,2,2). Default value: None. reference_thetas : None or list of (ndarray or None), optional Reference points from which the distances are calculated. If None, the origin (0,0) is used. Default value: None. contour_distance : float, optional. Distance threshold at which the contours are drawn. Default value: 1. xlabel : str, optional Label for the x axis. Default value: r'$\theta_0$'. ylabel : str, optional Label for the y axis. Default value: r'$\theta_1$'. xrange : tuple of float, optional Range `(min, max)` for the x axis. Default value: (-1., 1.). yrange : tuple of float, optional Range `(min, max)` for the y axis. Default value: (-1., 1.). labels : None or list of (str or None), optional Legend labels for the contours. Default value: None. inline_labels : None or list of (str or None), optional Inline labels for the contours. Default value: None. resolution : int Number of points per axis for the calculation of the distances. Default value: 500. colors : None or str or list of str, optional Matplotlib line (and error band) colors for the contours. If None, uses default colors. Default value: None. linestyles : None or str or list of str, optional Matploitlib line styles for the contours. If None, uses default linestyles. Default value: None. linewidths : float or list of float, optional Line widths for the contours. Default value: 1.5. alphas : float or list of float, optional Opacities for the contours. Default value: 1. alphas_uncertainties : float or list of float, optional Opacities for the error bands. Default value: 0.25. Returns ------- figure : Figure Plot as Matplotlib Figure instance. """ # Input data fisher_information_matrices = np.asarray(fisher_information_matrices) n_matrices = fisher_information_matrices.shape[0] if fisher_information_matrices.shape != (n_matrices, 2, 2): raise RuntimeError( "Fisher information matrices have shape {}, not (n, 2,2)!".format( fisher_information_matrices.shape)) if fisher_information_covariances is None: fisher_information_covariances = [None for _ in range(n_matrices)] if reference_thetas is None: reference_thetas = [None for _ in range(n_matrices)] d2_threshold = contour_distance**2.0 # Line formatting if colors is None: colors = ["C" + str(i) for i in range(10)] * (n_matrices // 10 + 1) elif not isinstance(colors, list): colors = [colors for _ in range(n_matrices)] if linestyles is None: linestyles = ["solid", "dashed", "dotted", "dashdot" ] * (n_matrices // 4 + 1) elif not isinstance(linestyles, list): linestyles = [linestyles for _ in range(n_matrices)] if not isinstance(linewidths, list): linewidths = [linewidths for _ in range(n_matrices)] if not isinstance(alphas, list): alphas = [alphas for _ in range(n_matrices)] if not isinstance(alphas_uncertainties, list): alphas_uncertainties = [ alphas_uncertainties for _ in range(n_matrices) ] # Grid xi = np.linspace(xrange[0], xrange[1], resolution) yi = np.linspace(yrange[0], yrange[1], resolution) xx, yy = np.meshgrid(xi, yi, indexing="xy") xx, yy = xx.flatten(), yy.flatten() thetas = np.vstack((xx, yy)).T # Theta from reference thetas d_thetas = [] for reference_theta in reference_thetas: if reference_theta is None: d_thetas.append(thetas) else: d_thetas.append(thetas - reference_theta) d_thetas = np.array(d_thetas) # Shape (n_matrices, n_thetas, n_parameters) # Calculate Fisher distances fisher_distances_squared = np.einsum("mni,mij,mnj->mn", d_thetas, fisher_information_matrices, d_thetas) fisher_distances_squared = fisher_distances_squared.reshape( (n_matrices, resolution, resolution)) # Calculate uncertainties of Fisher distances fisher_distances_squared_uncertainties = [] for d_theta, inf_cov in zip(d_thetas, fisher_information_covariances): if inf_cov is None: fisher_distances_squared_uncertainties.append(None) continue var = np.einsum("ni,nj,ijkl,nk,nl->n", d_theta, d_theta, inf_cov, d_theta, d_theta) uncertainties = (var**0.5).reshape((resolution, resolution)) fisher_distances_squared_uncertainties.append(uncertainties) logger.debug("Std: %s", uncertainties) # Plot results fig = plt.figure(figsize=(5.0, 5.0)) # Error bands for i in range(n_matrices): if fisher_information_covariances[i] is not None: d2_up = fisher_distances_squared[ i] + fisher_distances_squared_uncertainties[i] d2_down = fisher_distances_squared[ i] - fisher_distances_squared_uncertainties[i] band = (d2_up > d2_threshold) * (d2_down < d2_threshold) + ( d2_up < d2_threshold) * (d2_down > d2_threshold) plt.contourf(xi, yi, band, [0.5, 2.5], colors=colors[i], alpha=alphas_uncertainties[i]) # Predictions for i in range(n_matrices): cs = plt.contour( xi, yi, fisher_distances_squared[i], np.array([d2_threshold]), colors=colors[i], linestyles=linestyles[i], linewidths=linewidths[i], alpha=alphas[i], label=None if labels is None else labels[i], ) if inline_labels is not None and inline_labels[i] is not None and len( inline_labels[i]) > 0: plt.clabel(cs, cs.levels, inline=True, fontsize=12, fmt={d2_threshold: inline_labels[i]}) # Legend and decorations if labels is not None: plt.legend() plt.axes().set_xlim(xrange) plt.axes().set_ylim(yrange) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.tight_layout() return fig
def present_plane(file_in, plane): """ open visualisation file and make desired plots of that plane """ if os.path.isfile(file_in + '_visual_' + plane + '.fits.gz'): file_path = file_in + '_visual_' + plane + '.fits.gz' fits = pf.open(file_path) data_in = fits[0].data n_dust = fits[0].header['N_DUST'] pix = fits[0].header['NAXIS1'] r_ou = (pix - 1) / 2 * fits[0].header['CDELT1'] xlab = 'distance [%s]' % (fits[0].header['CUNIT1']) ylab = xlab fits.close() pic = np.zeros((pix, pix, 8 + 2 * n_dust)) for i in range(8 + 2 * n_dust): pic[:, :, i] = data_in[i, :, :] ext = file_path[-10:-8] + '-plane' m_range = [-r_ou, r_ou, -r_ou, r_ou] else: file_path = file_in + '_visual_' + plane + '.dat' map_in = open(file_path) row = map_in.readline().split() map_size = int(row[0]) row = map_in.readline() # empty row n_dust = 1 # fixed value here for j in range(map_size): for k in range(map_size): row = map_in.readline().split() if j == 0 and j == 0: len_pic = len(row) pic = np.zeros((map_size, map_size, len_pic - 2)) if j == 0 and k == 0: j_min = float(row[0]) k_min = float(row[1]) elif j == map_size - 1 and k == map_size - 1: j_max = float(row[0]) k_max = float(row[1]) for l in range(2, len_pic): if row[l] == 'NaN': pic[k, j, l - 2] = 0 else: pic[k, j, l - 2] = row[l] m_range = [k_min, k_max, j_min, j_max] ext = file_path[-6:-4] + '-plane' xlab = 'distance [AU]' ylab = xlab #~ pic += 1e-250 #------------------------------------------------- # Dust Temp for i in range(n_dust): plt.figure('Dust %2.0d Temperature, %s' % (i + 1, ext)) plt.title('Dust %2.0d Temperature, %s' % (i + 1, ext)) plt.xlabel(xlab) plt.ylabel(ylab) cont = [10, 20, 25, 30, 35, 40] data = pic[:, :, 4 + n_dust + i] CS = plt.contour(data, cont, linewidths=1, colors='k', extent=m_range) plt.clabel(CS, inline=1, fmt='%2.1f', fontsize=10) plt.imshow(data, extent=m_range, origin='lower', interpolation='None', cmap=plt.cm.jet) plt.clim(0, 350) plt.colorbar().set_label('Temperature [K]') #------------------------------------------------- # Gas Temp plt.figure('Gas Temperature, ' + ext) plt.title('Gas Temperature, ' + ext) plt.xlabel(xlab) plt.ylabel(ylab) cont = [10, 20, 25, 30, 35, 40] data = pic[:, :, 4 + 2 * n_dust] CS = plt.contour(data, cont, linewidths=1, colors='k', extent=m_range) plt.clabel(CS, inline=1, fmt='%2.1f', fontsize=10) plt.imshow(data, extent=m_range, origin='lower', interpolation='None', cmap=plt.cm.jet) plt.clim(0, 350) plt.colorbar().set_label('Temperature [K]') #------------------------------------------------- # Velocity plt.figure('abs(Velocity), ' + ext) plt.title('abs(Velocity), ' + ext) plt.xlabel(xlab) plt.ylabel(ylab) if pic.shape[2] > 9: data = np.sqrt(pic[:, :, 5 + 2 * n_dust]**2 + pic[:, :, 6 + 2 * n_dust]**2 + pic[:, :, 7 + 2 * n_dust]**2) / 1000 else: data = pic[:, :, 5 + 2 * n_dust] CS = plt.contour(data, linewidths=1, colors='k', extent=m_range) plt.clabel(CS, inline=1, fmt='%2.1f', fontsize=10) plt.imshow(data, extent=m_range, origin='lower', interpolation='None', cmap=plt.cm.jet) plt.colorbar().set_label('Velocity [km/s]') #------------------------------------------------- # molecule density data = pic[:, :, 0 + n_dust] * 1e-6 plt.figure('Molecule distribution, ' + ext) plt.title('Molecule distribution, ' + ext) plt.xlabel(xlab) plt.ylabel(ylab) vmax = np.max(data) vmin = vmax * 1e-6 cont = 10.0**np.linspace(np.log10(vmin), np.log10(vmax), 7) CS = plt.contour(data, levels=cont, linewidths=1, colors='k', extent=m_range) plt.clabel(CS, inline=1, fmt='%2.1e', fontsize=10) plt.imshow(data, extent=m_range, origin='lower', interpolation='None', cmap=plt.cm.jet, norm=LogNorm(vmin=vmin, vmax=vmax)) plt.colorbar().set_label('molecule density [cm$^{-3}$]') #------------------------------------------------- # dust density for i in range(n_dust): data = pic[:, :, i] * 1e-6 plt.figure('Dust %2.0d distribution, %s' % (i + 1, ext)) plt.title('Dust %2.0d distribution, %s' % (i + 1, ext)) plt.xlabel(xlab) plt.ylabel(ylab) vmax = np.max(data) vmin = vmax * 1e-6 cont = 10.0**np.linspace(np.log10(vmin), np.log10(vmax), 7) CS = plt.contour(data, levels=cont, linewidths=1, colors='k', extent=m_range) plt.clabel(CS, inline=1, fmt='%2.1e', fontsize=10) plt.imshow(data, extent=m_range, origin='lower', interpolation='None', cmap=plt.cm.jet, norm=LogNorm(vmin=vmin, vmax=vmax)) plt.colorbar().set_label('dust density [cm$^{-3}$]') #------------------------------------------------- # H2 density data = pic[:, :, 1 + n_dust] * 1e-6 plt.figure('H2 distribution, ' + ext) plt.title('H2 distribution, ' + ext) plt.xlabel(xlab) plt.ylabel(ylab) vmax = np.max(data) vmin = vmax * 1e-6 cont = 10.0**np.linspace(np.log10(vmin), np.log10(vmax), 7) CS = plt.contour(data, levels=cont, linewidths=1, colors='k', extent=m_range) plt.clabel(CS, inline=1, fmt='%2.1e', fontsize=10) plt.imshow(data, extent=m_range, origin='lower', interpolation='None', cmap=plt.cm.jet, norm=LogNorm(vmin=vmin, vmax=vmax)) plt.colorbar().set_label('H2 number density [cm$^{-3}$]') #------------------------------------------------- # N(Mol)/N(H) fig = plt.figure('N(mol)/N(H), ' + ext) H2 = pic[:, :, 1 + n_dust] Mol = pic[:, :, 0 + n_dust] data = np.zeros_like(H2) idn = np.where(H2 > 0) data[idn] = Mol[idn] / H2[idn] * 0.5 plt.xlabel(xlab) plt.ylabel(ylab) vmax = np.max(data) vmin = vmax * 1e-6 #~ m_range = [-100,100,-40,40] cont = 10.0**np.linspace(np.log10(vmin), np.log10(vmax), 7) CS = plt.contour(data[:, :], levels=cont, linewidths=1, colors='k', extent=m_range) plt.clabel(CS, inline=1, fmt='%2.1e', fontsize=10) plt.imshow(data[:, :], extent=m_range, origin='lower', interpolation='None', cmap=plt.cm.jet, norm=LogNorm(vmin=vmin, vmax=vmax)) plt.colorbar().set_label(r'N(HCO$^{+}$)/N(H)')
# Define a nice function of distance from individual pts def f(x, y, pts): z = np.zeros_like(x) for p in pts: z = z + 1 / (np.sqrt((x - p[0])**2 + (y - p[1])**2)) return 1 / z X, Y = np.meshgrid(np.linspace(-1, 1, 51), np.linspace(-1, 1, 51)) Z = f(X, Y, pts) CS = plt.contour(X, Y, Z, 20) tellme('Use mouse to select contour label locations, middle button to finish') CL = plt.clabel(CS, manual=True) ################################################## # Now do a zoom tellme('Now do a nested zoom, click to begin') plt.waitforbuttonpress() while True: tellme('Select two corners of zoom, middle mouse button to finish') pts = plt.ginput(2, timeout=-1) if len(pts) < 2: break (x0, y0), (x1, y1) = pts xmin, xmax = sorted([x0, x1]) ymin, ymax = sorted([y0, y1])
LZ = np.linspace(lzmin, lzmax, 100)[np.newaxis, :] phase = np.exp(-2 * factor * LZ) multiple_reflections = -T * Ts * phase / (1 + Rs * phase) S11 = R + multiple_reflections Z = np.abs(S11)**2 [X, Y] = np.meshgrid(LZ.flatten(), f.flatten()) fig, ax = plt.subplots(figsize=(10, 10)) cax = ax.pcolor(X * 1e3, Y / 1e9, Z, cmap="RdGy", alpha=0.75, vmin=0, vmax=1) cbar = plt.colorbar(cax, label="Reflection") ax.tick_params('both', labelsize=14) contours = plt.contour(X * 1e3, Y / 1e9, Z, [0.1, 0.5], colors="black") plt.clabel(contours, inline=True, fontsize=12, manual=[(2, 5), (2, 7.5), (4, 7), (4, 11)], fmt="%.1f", inline_spacing=15) plt.xlabel("lz [mm]", fontsize=14) plt.ylabel("f [GHz]") plt.title( "Cu patch edge length L=%s mm, $\epsilon=$ %s + i%s/2$\pi f \epsilon_0$" % (L, eps, kappa)) plt.savefig("XBandAbsorber_withoutR.pdf", format="pdf") to_write = np.zeros((len(f), 5)) to_write[:, 0] = f to_write[:, 1] = np.real(R[:, 0]) to_write[:, 2] = np.imag(R[:, 0]) to_write[:, 3] = np.real(multiple_reflections[:, 59])
def plot_traj_MDN_mult(model, sess, val_dict, batch, sl_plot=5, ind=-1): """Plots the trajectory. At given time-stamp, it plots the probability distributions of where the next point will be THIS IS FOR MULTIPLE MIXTURES input: - sess: the TF session - val_dict: a dictionary with which to evaluate the model - batch: the batch X_val[some_indices] that you feed into val_dict. we could also pick this from val-dict, but this workflow is cleaner - sl_plot: the time-stamp where you'd like to visualize - ind: some index into the batch. if -1, we'll pick a random one""" result = sess.run([ model.mu1, model.mu2, model.mu3, model.s1, model.s2, model.s3, model.rho, model.theta ], feed_dict=val_dict) batch_size, crd, seq_len = batch.shape assert ind < batch_size, 'Your index is outside batch' assert sl_plot < seq_len, 'Your sequence index is outside sequence' if ind == -1: ind = np.random.randint(0, batch_size) delta = 0.025 #Grid size to evaluate the PDF width = 1.0 # how far to evaluate the pdf? fig = plt.figure() ax = fig.add_subplot(2, 2, 1, projection='3d') ax.plot(batch[ind, 0, :], batch[ind, 1, :], batch[ind, 2, :], 'r') ax.scatter(batch[ind, 0, sl_plot], batch[ind, 1, sl_plot], batch[ind, 2, sl_plot]) ax.set_xlabel('x coordinate') ax.set_ylabel('y coordinate') ax.set_zlabel('z coordinate') # lower-case x1,x2,x3 are indezing the grid # upper-case X1,X2,X3 are coordinates in the mesh x1 = np.arange(-width, width + 0.1, delta) x2 = np.arange(-width, width + 0.2, delta) x3 = np.arange(-width, width + 0.3, delta) X1, X2, X3 = np.meshgrid(x1, x2, x3, indexing='ij') XX = np.stack((X1, X2, X3), axis=3) PP = [] mixtures = result[0].shape[1] for m in range(mixtures): mean = np.zeros((3)) mean[0] = result[0][ind, m, sl_plot] mean[1] = result[1][ind, m, sl_plot] mean[2] = result[2][ind, m, sl_plot] cov = np.zeros((3, 3)) sigma1 = result[3][ind, m, sl_plot] sigma2 = result[4][ind, m, sl_plot] sigma3 = result[5][ind, m, sl_plot] sigma12 = result[6][ind, m, sl_plot] * sigma1 * sigma2 cov[0, 0] = np.square(sigma1) cov[1, 1] = np.square(sigma2) cov[2, 2] = np.square(sigma3) cov[1, 2] = sigma12 cov[2, 1] = sigma12 rv = multivariate_normal(mean, cov) P = rv.pdf(XX) #P is now in [x1,x2,x3] PP.append(P) # PP is now a list PP = np.stack(PP, axis=3) # PP is now in [x1,x2,x3,mixtures] #Multiply with the mixture theta_local = result[7][ind, :, sl_plot] ZZ = np.dot(PP, theta_local) #ZZ is now in [x1,x2,x3] print('The theta variables %s' % theta_local) #Every Z is a marginalization of ZZ. # summing over axis 2, gives the pdf over x1,x2 # summing over axis 1, gives the pdf over x1,x3 # summing over axis 0, gives the pdf over x2,x3 ax = fig.add_subplot(2, 2, 2) X1, X2 = np.meshgrid(x1, x2) Z = np.sum(ZZ, axis=2) CS = ax.contour(X1, X2, Z.T) plt.clabel(CS, inline=1, fontsize=10) ax.set_xlabel('x coordinate') ax.set_ylabel('y coordinate') ax = fig.add_subplot(2, 2, 3) X1, X3 = np.meshgrid(x1, x3) Z = np.sum(ZZ, axis=1) CS = ax.contour(X1, X3, Z.T) plt.clabel(CS, inline=1, fontsize=10) ax.set_xlabel('x coordinate') ax.set_ylabel('Z coordinate') ax = fig.add_subplot(2, 2, 4) X2, X3 = np.meshgrid(x2, x3) Z = np.sum(ZZ, axis=0) CS = ax.contour(X2, X3, Z.T) plt.clabel(CS, inline=1, fontsize=10) ax.set_xlabel('y coordinate') ax.set_ylabel('Z coordinate')
plt.plot(alpha, f, "ro") x1 = np.arange(n / Lx) * pi y1 = x1 * 0 plt.plot(x1, y1, "g+") axes = plt.gca() axes.set_ylim([-1, 1]) plt.show() print(alpha) print(np.arange(len(alpha)) * pi / 2) print(alpha * np.tan(Lx * alpha) - beta) print(np.arange(n) * pi / 2) if disp: Tanaly = analy(T1, Ta, h, lamb, Lx, Ly, Nx, Ny, n=n, err=err) X = np.arange(Tanaly.shape[0]) / Nx * Lx Y = np.arange(Tanaly.shape[1]) / Ny * Ly fig, ax3 = plt.subplots(figsize=(8, 6)) im = ax3.pcolormesh(Y, X, Tanaly) im2 = ax3.contour(Y, X, Tanaly, colors="k") plt.clabel(im2, inline=1, fontsize=10) zou = fig.colorbar(im) zou.ax.set_ylabel('Température en Kelvin') plt.title("Analytic") ax3.set_xlabel('x(m)') ax3.set_ylabel('y(m)')
print(data['val'].max()) print(data['val'].min()) #brings the data in a matrix form hours above days data_matrix = data['val'].reshape((24, 365)) a = np.transpose(data_matrix) #print(data_matrix) # Create a simple contour plot with labels using default colors. The # inline argument to clabel will control whether the labels are draw # over the line segments of the contour, removing the lines beneath # the label plt.figure() CS = plt.contour(data_matrix) plt.clabel(CS, inline=1, fontsize=10) plt.title('Simplest default with labels') # You can force all the contours to be the same color. plt.figure() CS = plt.contour( data_matrix, 6, colors='k', # negative contours will be dashed by default ) plt.clabel(CS, inline=1, fontsize=9) plt.title('Single color - negative contours dashed') # You can set negative contours to be solid instead of dashed: matplotlib.rcParams['contour.negative_linestyle'] = 'solid' plt.figure()
def main(): dimension_number, exp_number = 2, 20 x_min_dist, x_max_dist, y_min_dist, y_max_dist, x0, dot_num, points_seq_style, way_style, exact_solution_style, \ figsize, uniform_distr_low, uniform_distr_high, calc_epsilon, min_dist_between_points, level_max_diff = \ -10.0, 10.0, -10.0, 10.0, [0, 0], 500, 'ko', 'k-', 'ro', (15, 7.5), -5, 5, 1e-4, 1, 1000 a, b, c = \ rand(dimension_number, dimension_number) * (uniform_distr_high - uniform_distr_low) + uniform_distr_low, \ rand(dimension_number) * (uniform_distr_high - uniform_distr_low) + uniform_distr_low, 0 for j in range(exp_number): b = rand(dimension_number) * (uniform_distr_high - uniform_distr_low) + uniform_distr_low while True: a = rand(dimension_number, dimension_number) * ( uniform_distr_high - uniform_distr_low) + uniform_distr_low hessian_of_f = (a + a.T) / 2 flag = False for i in range(dimension_number): if linalg.det(hessian_of_f[:i + 1, :i + 1]) < 1e-15: flag = True break if not flag: break exact_solution = linalg.solve(hessian_of_f, b) x0 = rand(dimension_number) x0[0] = x0[0] * (x_max_dist - x_min_dist) + exact_solution[0] + x_min_dist x0[1] = x0[1] * (y_max_dist - y_min_dist) + exact_solution[1] + y_min_dist points_seq, _ = r_algorithm(f, x0, args=(a, b, c), form='B', calc_epsilon=calc_epsilon, iter_lim=100, step_method='adaptive', default_step=10, step_red_mult=0.75, step_incr_mult=1.25, lim_num=3, reduction_epsilon=1e-15) argmin = points_seq[points_seq.shape[0] - 1] count = 0 while count < points_seq.shape[0] - 1: if linalg.norm(points_seq[count] - points_seq[count + 1]) < min_dist_between_points: points_seq = np.delete(points_seq, count + 1, 0) count -= 1 count += 1 points_seq = np.append(points_seq, argmin).reshape(points_seq.shape[0] + 1, 2) levels = np.sort( f(np.array([points_seq[:, 0], points_seq[:, 1]]), (a, b, c))) count = 0 while count < levels.size - 1: if levels[count + 1] - levels[count] > level_max_diff: levels = np.insert(levels, count + 1, (levels[count + 1] + levels[count]) / 2.0) count -= 1 count += 1 levels = np.array(list(set(levels))) levels.sort() x, y = \ np.linspace(exact_solution[0] + x_min_dist, exact_solution[0] + x_max_dist, dot_num), \ np.linspace(exact_solution[1] + y_min_dist, exact_solution[1] + y_max_dist, dot_num) xx, yy = np.meshgrid(x, y) z = f(np.array([xx, yy]), (a, b, c)) plt.figure(figsize=figsize) plt.grid(True) numerical_contour = plt.contour(x, y, z, levels=levels) plt.clabel(numerical_contour, inline=1, fontsize=10) plt.plot(points_seq[:, 0], points_seq[:, 1], points_seq_style, label=u"Наближення") for i in range(points_seq.shape[0] - 1): plt.plot([points_seq[i][0], points_seq[i + 1][0]], [points_seq[i][1], points_seq[i + 1][1]], way_style) plt.plot(exact_solution[0], exact_solution[1], exact_solution_style) plt.show() plt.close()
p.figure(1, figsize=(8, 8)) axScatter = p.axes(rect_scatter) axScatter.set_yscale('log') axScatter.set_xscale('log') extent = [yedges[0], yedges[-1], xedges[0], xedges[-1]] levels = (0.01, 0.1, 0.5, 1) cset = p.contour(X, Y, proba, levels, origin='lower', colors=['black', 'green', 'blue', 'red'], linewidths=(1.9, 1.6, 1.5, 1.4), extent=extent) p.clabel(cset, inline=1, fontsize=10, fmt='%1.0i') for c in cset.collections: c.set_linestyle('solid') p.xlabel('DF N1') p.ylabel('DF') axHistx = p.axes(rect_histx) axHisty = p.axes(rect_histy) # no labels axHistx.xaxis.set_major_formatter(nullfmt) axHisty.yaxis.set_major_formatter(nullfmt) # the scatter plot: axHistx.plot(xb, HDF1, 'k')
Y_idx, RESULT_STRESS, alpha=.8, cmap='RdYlGn_r', levels=levels) plt.colorbar(shrink=0.5, aspect=len(levels), label="nomalized cumulative stress over gait") plt.clim(0, 50) surf = plt.contour(X_idx, Y_idx, RESULT_STRESS, levels=levels, colors='black') plt.clabel(surf, levels, inline=True, fmt='%2.0f', fontsize=25) low_res = [] gait_tex = '' for c1_idx in range(len(C1)): if c1_idx % take_every == 0 or c1_idx == len(C1) - 1: low_res += [1] * len(X2) else: low_res += [0] * len(X2) for g_idx, gait in enumerate(GAITS): if low_res[g_idx] == 1: gait.plot_orientation(length=.7 * sc, w=.5, size=6) # gait.plot_gait() gait_tex = (gait_tex + '\n%%%%%%%\n' + gait.get_tikz_repr(linewidth='.7mm', dashed=0))
def plots_IMSHOW_cc(_snap, _x1, _x2, _pr, _limx1, _limx2, _limpr, _ngrid, _ncont_levels, _text, _paths, _filename): limx1 = _limx1 limx2 = _limx2 limp = _limpr textbar = _text x1 = _x1 x2 = _x2 p = _pr ng = _ngrid ncl = _ncont_levels #plot fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111) [X, Y] = np.meshgrid(np.linspace(np.min(x1), np.max(x1), ng), np.linspace(np.min(x2), np.max(x2), ng)) Z = griddata(x1, x2, p, X, Y, interp='linear') map_prop = ax.imshow(Z, vmin=limp[0], vmax=limp[1], cmap='jet', origin='lower') cont_prop = ax.contour(Z, levels=np.linspace(limp[0], limp[1], ncl), cmap='Greys_r', linewidths=1.2) #cmap='gist_rainbow_r',lw=0.2 ) plt.clabel(cont_prop, inline=1, fontsize=20, colors='k') locsx, labelsx = plt.xticks() labelsx = [str(i * (2 * limx1[1] / float(ng)) - limx1[1]) for i in locsx] tick_locsx = locsx tick_lblsx = labelsx plt.xticks(tick_locsx[1:], tick_lblsx[1:]) locsy, labelsy = plt.yticks() labelsy = [str(i * (2 * limx2[1] / float(ng)) - limx2[1]) for i in locsy] tick_locsy = locsy tick_lblsy = labelsy plt.yticks(tick_locsy[1:], tick_lblsy[1:]) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = fig.colorbar(map_prop, cax=cax, label=textbar, ticks=np.linspace(limp[0], limp[1], ncl)) cbar.add_lines(cont_prop) time = _snap[9::] ax.minorticks_on() plt.text(0.87, 0.92, "t=" + time, ha='center', va='center', transform=ax.transAxes, color="#ffa74e") path = _paths + 'cc_' + '_' + _filename + '_' + str(time) + '.jpg' plt.savefig(path, dpi=100, bbox_inches='tight')
bath_elevsub, levels=[0, 10000], colors='papayawhip', alpha=0.5) plt.contourf(lonGOFS[oklonGOFS] - 360, latGOFS[oklatGOFS], NPEA_GOFS_100 * 1000, cmap=cmocean.cm.deep_r, **kw) cb = plt.colorbar() cs = plt.contour(lonGOFS[oklonGOFS] - 360, latGOFS[oklatGOFS], NPEA_GOFS_100 * 1000, [-0.35], color='k') fmt = '%r' plt.clabel(cs, fmt=fmt) plt.axis('scaled') cb.set_label('Stratification Factor ($x1000$)', rotation=270, labelpad=20, fontsize=14) plt.title('Non-Dimensional Potential Energy Anomaly 100 m\n GOFS on '+str(tGOFS[oktimeGOFS[4]])[0:13],\ fontsize=16) file = folder_fig + 'MAB_NPEA_100m_GOFS' plt.savefig(file, bbox_inches='tight', pad_inches=0.1) #%% NPEA COP kw = dict(levels=np.arange(-0.56, 0, 0.05)) fig, ax = plt.subplots(figsize=(6, 6))
def plot_2d_contour(x_coords, y_coords, z_values, magnitude, base_name, vmin=0.1, vmax=10, vlevel=0.5, show=False, plot_type='mesh', file_type="png", dir1_scale=1., dir2_scale=1., dir1_name="dim1", dir2_name="dim2", env_name=None, key_name=None, logscale="auto"): """Plot 2D contour map and 3D surface.""" X = x_coords Y = y_coords Z = z_values title = env_name # Remove Atari name options env_name = env_name.replace("NoFrameskip", "") env_name = env_name.replace("-v0", "") env_name = env_name.replace("-v1", "") env_name = env_name.replace("-v2", "") env_name = env_name.replace("-v3", "") env_name = env_name.replace("-v4", "") env_name = env_name.replace("-v5", "") env_name = env_name.replace("Deterministic", "") # Construct Title if env_name in ENVCLASSES: title += " | " + ENVCLASSES[env_name] else: warnings.warn( "Environment is not listed in reward_surfaces/utils/plot_utils.py, plots titles may be missing information." ) if env_name in REWARDCLASSES: title += " | " + REWARDCLASSES[env_name] # Label max value if key_name in KEYNAMES: title += " | " + f"{KEYNAMES[key_name]}" #title += " | " + f"Max {KEYNAMES[key_name]}: {np.max(Z):.02f}" else: title += " | " + "Value" #title += " | " + f"Max Value: {np.max(Z):.02f}" # Automatically choose logscale if logscale == "auto": if np.max(Z) - np.min(Z) > 10000: logscale = True elif logscale == "on": logscale = True else: logscale = False # -------------------------------------------------------------------- # Plot 2D contours # -------------------------------------------------------------------- if plot_type == 'all' or plot_type == 'contour': fig = plt.figure() CS = plt.contour(X, Y, Z, cmap='summer', levels=np.arange(vmin, vmax, vlevel)) plt.clabel(CS, inline=1, fontsize=8) out_fname = base_name + '_2dcontour.' + file_type fig.savefig(out_fname, dpi=300, bbox_inches='tight', format=file_type) if plot_type == 'all' or plot_type == 'contourf': fig = plt.figure() print(base_name + '_2dcontourf' + '.png') CS = plt.contourf(X, Y, Z, cmap='summer', levels=np.arange(vmin, vmax, vlevel)) out_fname = base_name + '_2dcontourf.' + file_type fig.savefig(out_fname, dpi=300, bbox_inches='tight', format=file_type) # -------------------------------------------------------------------- # Plot 2D heatmaps # -------------------------------------------------------------------- if plot_type == 'all' or plot_type == 'heat': if file_type != "pgf": sns.set_theme(font="Serif") dir1_name = "Grad Direction" dir2_name = "Random Direction" size = len(X[0]) dir1_magnitude = math.floor(math.log10(abs(dir1_scale))) dir2_magnitude = math.floor(math.log10(abs(dir2_scale))) labels_d1 = [ f"{x:0.1f}" for x in (np.arange(size) - size // 2) / (size / 2) * dir1_scale * (10**-dir1_magnitude) ] labels_d2 = [ f"{x:0.1f}" for x in (np.arange(size) - size // 2) / (size / 2) * dir2_scale * (10**-dir2_magnitude) ] ax = plt.axes() sns_plot = sns.heatmap(Z, cmap='viridis', cbar=True, vmin=vmin, vmax=vmax, xticklabels=labels_d1, yticklabels=labels_d2) sns_plot.invert_yaxis() xlabel = dir1_name + r" ($10^{{{}}}$)".format( dir1_magnitude) if dir1_magnitude != 0 else dir1_name ylabel = dir2_name + r" ($10^{{{}}}$)".format( dir2_magnitude) if dir2_magnitude != 0 else dir2_name sns_plot.set(xlabel=xlabel, ylabel=ylabel) out_fname = base_name + '_2dheat.' + file_type ax.set_title(title) sns_plot.get_figure().savefig(out_fname, dpi=300, bbox_inches='tight', format=file_type) # -------------------------------------------------------------------- # Plot 3D surface # -------------------------------------------------------------------- if plot_type == 'all' or plot_type == 'mesh': fig = plt.figure() tnrfont = {'fontname': 'Sans'} ax = Axes3D(fig) fig.suptitle(title) if file_type != "pgf": fig.suptitle(title, **tnrfont) if np.min(Z) < -1e9 and not logscale: print( "Warning: Data includes extremely large negative rewards ({:3E}).\ Consider setting logscale=True".format(np.min(Z))) # Scale X and Y values by the step size magnitude X = magnitude * X Y = magnitude * Y real_Z = Z.copy() # Take numerically stable log of data if logscale: Z_neg = Z[Z < 0] Z_pos = Z[Z >= 0] Z_neg = -np.log10(1 - Z_neg) Z_pos = np.log10(1 + Z_pos) Z[Z < 0] = Z_neg Z[Z >= 0] = Z_pos # Plot surface surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False, zorder=5) # Add max text # center = len(Z) // 2 # ax.text(0.05, 0.05, np.max(Z), f"{real_Z[center][center]:.2f}", color='black') # Plot center line above surface Z_range = abs(np.max(Z) - np.min(Z)) zline_above = np.linspace(Z[len(Z) // 2][len(Z[0]) // 2], np.max(Z) + (Z_range * 0.1), 4) xline_above = 0 * zline_above yline_above = 0 * zline_above ax.plot3D(xline_above, yline_above, zline_above, 'black', zorder=10) # Plot center line below surface zline_below = np.linspace(Z[len(Z) // 2][len(Z[0]) // 2], np.min(Z) - (Z_range * 0.1), 4) xline_below = 0 * zline_below yline_below = 0 * zline_below ax.plot3D(xline_below, yline_below, zline_below, 'black', zorder=0) # Fix colorbar labeling for log scale if logscale: # Find the highest order of magnitude max_Z = np.max(real_Z) if max_Z < 0: max_magnitude = -math.floor(math.log10(-max_Z)) else: max_magnitude = math.floor(math.log10(max_Z)) # Find the lowest order of magnitude min_Z = np.min(real_Z) if min_Z < 0: min_magnitude = -math.floor(math.log10(-min_Z)) else: if min_Z == 0: min_Z += 0.0000001 min_magnitude = math.floor(math.log10(min_Z)) # Create colorbar continuous_labels = np.round( np.linspace(min_magnitude, max_magnitude, 8, endpoint=True)) cbar = fig.colorbar(surf, shrink=0.5, aspect=5, ticks=continuous_labels, pad=0.1) cbar.set_ticks(list()) # Manually set colorbar and z axis tick text zticks = [] ztick_labels = [] bounds = cbar.ax.get_ybound() for index, label in enumerate(continuous_labels): x = 6.0 y = bounds[0] + (bounds[1] - bounds[0]) * index / 8 # Format label zticks.append(label) if label > 2 or label < -2: label = "$-10^{" + str( int(-label)) + "}$" if label < 0 else "$10^{" + str( int(label)) + "}$" else: label = "${}$".format(-10.0**( -label)) if label < 0 else "${}$".format(10.0**label) cbar.ax.text(x, y, label) ztick_labels.append(" " + label) ax.set_zticks(zticks) ax.set_zticklabels(ztick_labels) if file_type != "pgf": ax.set_zticklabels(ztick_labels, **tnrfont) else: fig.colorbar(surf, shrink=0.5, aspect=5, pad=0.05) # Save plot out_fname = base_name + '_3dsurface.' + file_type fig.savefig(out_fname, dpi=300, bbox_inches='tight', format=file_type) if show: plt.show() return out_fname
levels=np.arange(40, 92, 10), extend='both', zorder=3) # 色标 cb = fig.colorbar(ac, extend='both', shrink=1, label='相对湿度(%)', pad=0.01) #温度 temp0 = temps.isel(longitude=46, latitude=80, time=tarray) temp_tT = temp0 - 273.15 temp_t = temp_tT.T tt = np.arange(-20, 32, 4) at = ax.contour(time, levs, temp_t, tt, linewidths=1, colors='red', zorder=4) #零值线加粗,目前想到的本办法 a0 = ax.contour(time, levs, temp_t, [0], linewidths=1.3, colors='red', zorder=5) #fmt参数使标注数字为整数,默认标注3位小数 plt.clabel(at, fontsize=11, fmt='%d', colors="k", inline=True) #标注0值线 plt.clabel(a0, fontsize=11, fmt='%d', colors="k", inline=True) #纬向风 v_windT = v_winds.isel(longitude=46, latitude=80, time=tarray) v_wind = v_windT.T abar = ax.barbs(time, levs, v_wind) plt.show()
def plot_grid(gwf, silent=True): verbose = not silent fs = USGSFigure(figure_type="map", verbose=verbose) bot = gwf.dis.botm.array fig, axes = create_figure() ax = axes[0] mm = flopy.plot.PlotMapView(gwf, ax=ax, extent=extents) bot_coll = mm.plot_array(bot, vmin=bmin, vmax=bmax) mm.plot_bc("CHD", color="cyan") cv = mm.contour_array( bot, levels=blevels, linewidths=0.5, linestyles=":", colors=bcolor, ) plt.clabel(cv, fmt="%1.0f") ax.set_xlabel("x-coordinate, in meters") ax.set_ylabel("y-coordinate, in meters") fs.remove_edge_ticks(ax) # legend ax = axes[1] ax.plot( -10000, -10000, lw=0, marker="s", ms=10, mfc="cyan", mec="cyan", label="Constant Head", ) ax.plot( -10000, -10000, lw=0.5, ls=":", color=bcolor, label="Bottom elevation contour, m", ) fs.graph_legend(ax, loc="center", ncol=2) cax = plt.axes([0.275, 0.125, 0.45, 0.025]) cbar = plt.colorbar( bot_coll, shrink=0.8, orientation="horizontal", cax=cax, ) cbar.ax.tick_params(size=0) cbar.ax.set_xlabel(r"Bottom Elevation, $m$") # save figure if config.plotSave: fpth = os.path.join( "..", "figures", "{}-grid{}".format(sim_name, config.figure_ext), ) fig.savefig(fpth) return
cs = ax.imshow(numpy.flipud(ratio), extent=(80, 111, 40, 80), aspect='auto', cmap=cmap, interpolation='nearest', norm=norm) fig.colorbar(cs) cs = ax.contour(hindex.value("F") - t, levels=[-5, -4, -3, -2, -1, 0, 2, 4, 6, 8, 10, 14, 20], extent=(80, 110, 40, 80), aspect='auto', colors='white') plt.clabel(cs, inline=1, fontsize=14, fmt='%.0f') #print numpy.shape(otmpf) #print numpy.shape(orelh) #ax.scatter(otmpf.value("F"), orelh) ax.set_xlim(80, 110) #ax.set_yticks([10,25,50,75,100]) ax.set_ylabel("Dew Point Temperature $^\circ$F") ax.set_xlabel(r"Air Temperature $^\circ$F") ax.set_title( "1933-2012 Des Moines Heat Index\ncontour is heat index delta at temp/dwp\npixels are observed frequencies [%] at that temperature" ) fig.tight_layout() #fig.colorbar(cs)
fig1.subplots_adjust(bottom=0.08) ####################################################### #Plotting temperature ####################################################### ax1 = fig1.add_subplot(311, axisbg='grey') zmin = T.min() zmax = 0 #plt.pcolor(Xgrid,depth,T,cmap='Blues_r',vmin=zmin,vmax=zmax) plt.pcolor(Xgrid, depth, T, cmap=T_cmap, vmin=zmin, vmax=zmax) c1 = plt.colorbar(pad=0.01) c1.set_label(r'T') plt.axis([Xgrid.min(), Xgrid.max(), ymin, ymax]) #ax1.fill_between(Xaxis[:],freeboard[:], snow[:,0]+freeboard[:,],facecolor='white',edgecolor='white') CS1 = plt.contour(Xgrid, depth_contour, T, levelsT, colors='k') plt.clabel(CS1, fontsize=9, inline=1, fmt='%1.0f') plt.plot(Xaxis[:], freeboard[:], 'k--') plt.ylabel(r'depth [m]') ax1.set_title('Temperature, liquid volume fraction, and bulk salinity') ax1.xaxis.set_ticklabels([]) ####################################################### #Plotting liquid fraction ####################################################### ax2 = fig1.add_subplot(312, axisbg='grey') fsize = 10. zmin = 0. zmax = 1. #plt.pcolor(Xgrid,depth,psi_l,cmap='bone_r',vmin=zmin,vmax=zmax) plt.pcolor(Xgrid, depth, psi_l, cmap=psi_cmap, vmin=zmin, vmax=zmax)
def plot_results(idx, sim, silent=True): verbose = not silent if config.plotModel: fs = USGSFigure(figure_type="map", verbose=verbose) name = list(parameters.keys())[idx] sim_ws = os.path.join(ws, name) gwf = sim.get_model(sim_name) bot = gwf.dis.botm.array if idx == 0: plot_grid(gwf, silent=silent) # create MODFLOW 6 head object file_name = gwf.oc.head_filerecord.get_data()[0][0] fpth = os.path.join(sim_ws, file_name) hobj = flopy.utils.HeadFile(fpth) # create MODFLOW 6 cell-by-cell budget object file_name = gwf.oc.budget_filerecord.get_data()[0][0] fpth = os.path.join(sim_ws, file_name) cobj = flopy.utils.CellBudgetFile(fpth, precision="double") # extract heads and specific discharge head = hobj.get_data(totim=1.0) imask = (head > -1e30) & (head <= bot) head[imask] = -1e30 # botm[imask] spdis = cobj.get_data(text="DATA-SPDIS", totim=1.0) # Create figure for simulation fig, axes = create_figure() ax = axes[0] mm = flopy.plot.PlotMapView(gwf, ax=ax, extent=extents) if bot.max() < 20: cv = mm.contour_array( bot, levels=blevels, linewidths=0.5, linestyles=":", colors=bcolor, zorder=9, ) plt.clabel(cv, fmt="%1.0f", zorder=9) h_coll = mm.plot_array(head, vmin=vmin, vmax=vmax, masked_values=masked_values, zorder=10) cv = mm.contour_array( head, masked_values=masked_values, levels=vlevels, linewidths=0.5, linestyles="-", colors=vcolor, zorder=10, ) plt.clabel(cv, fmt="%1.0f", zorder=10) mm.plot_bc("CHD", color="cyan", zorder=11) mm.plot_specific_discharge(spdis, normalize=True, color="0.75", zorder=11) ax.set_xlabel("x-coordinate, in meters") ax.set_ylabel("y-coordinate, in meters") fs.remove_edge_ticks(ax) # create legend ax = axes[-1] ax.plot( -10000, -10000, lw=0, marker="s", ms=10, mfc="cyan", mec="cyan", label="Constant Head", ) ax.plot( -10000, -10000, lw=0, marker=u"$\u2192$", ms=10, mfc="0.75", mec="0.75", label="Normalized specific discharge", ) if bot.max() < 20: ax.plot( -10000, -10000, lw=0.5, ls=":", color=bcolor, label="Bottom elevation contour, m", ) ax.plot( -10000, -10000, lw=0.5, ls="-", color=vcolor, label="Head contour, m", ) fs.graph_legend(ax, loc="center", ncol=2) cax = plt.axes([0.275, 0.125, 0.45, 0.025]) cbar = plt.colorbar(h_coll, shrink=0.8, orientation="horizontal", cax=cax) cbar.ax.tick_params(size=0) cbar.ax.set_xlabel(r"Head, $m$", fontsize=9) # save figure if config.plotSave: fpth = os.path.join( "..", "figures", "{}-{:02d}{}".format(sim_name, idx + 1, config.figure_ext), ) fig.savefig(fpth)
def get_flux_vol(params): ''' Get 2D area and volume of flux surface ''' [I_l_opt,I_f_opt],[z_l_opt,z_f],[r_l_opt,r_f],[tz_l,tz_f],[tr_l,tr_f],[nz_l,nz_f],[nr_l,nr_f] = params X,Z,Bxm,Bzm,Bs,rAm=multicoil_fields([I_l_opt,I_f_opt],[z_l_opt,z_f],[r_l_opt,r_f],[tz_l,tz_f],[tr_l,tr_f],[nz_l,nz_f],[nr_l,nr_f]) if plt.fignum_exists(123): plt.clf() fig1 = plt.figure(123) axx=fig1.add_subplot(1,1,1, axisbg='b') phi= 2*np.pi*rAm; cs = plt.contourf(Z,X,phi*1e3,100,cmap=plt.cm.jet, extend="both") cbar=plt.colorbar() cbar.set_label(r' $2 \pi r A_{\theta} \times 10^3$',fontsize=16) levels=np.linspace(max(phi.flatten()*1.0e3)/5, max(phi.flatten()*1.0e3),100) CS = plt.contour(Z,X,phi*1.0e3,levels=levels,colors='w') plt.clabel(CS, inline=1, fontsize=13, linewidth=3, colors='white') plt.xlabel('r [m]'); plt.ylabel('z [m]') x_min,x_max=axx.get_xlim() y_min,y_max=axx.get_ylim() user_req=1 while user_req==1: contour_lv=float(raw_input('Within which contour level do you want to compute the area and volume? \n')) print "Click to get 4 corners within which to compute contour properties" coords=plt.ginput(4,show_clicks=True) plt.show(block=False) cc=np.asarray(coords) y_max=cc[:,1].max() y_min=cc[:,1].min() x_max=cc[:,0].max() x_min=cc[:,0].min() if plt.fignum_exists(222): plt.clf() fig2=plt.figure(222); y_max_idx=np.argmin(np.abs(X[0,:]-y_max)) y_min_idx=np.argmin(np.abs(X[0,:]-y_min)) x_max_idx=np.argmin(np.abs(Z[:,0]-x_max)) x_min_idx=np.argmin(np.abs(Z[:,0]-x_min)) contour_idx=np.argmin(np.abs(levels-contour_lv)) plt.contourf(Z[x_min_idx:x_max_idx,y_min_idx:y_max_idx],X[x_min_idx:x_max_idx,y_min_idx:y_max_idx],phi[x_min_idx:x_max_idx,y_min_idx:y_max_idx]*1.0e3, levels=levels) cs = plt.contour(Z[x_min_idx:x_max_idx,y_min_idx:y_max_idx],X[x_min_idx:x_max_idx,y_min_idx:y_max_idx],phi[x_min_idx:x_max_idx,y_min_idx:y_max_idx]*1.0e3,levels=levels,colors='w') plt.clabel(cs, inline=1, fontsize=13, linewidth=3, colors='white') plt.xlabel('r [m]'); plt.ylabel('z [m]') contour=cs.collections[contour_idx] vs=contour.get_paths()[0].vertices cs = plt.contour(Z[x_min_idx:x_max_idx,y_min_idx:y_max_idx],X[x_min_idx:x_max_idx,y_min_idx:y_max_idx],phi[x_min_idx:x_max_idx,y_min_idx:y_max_idx]*1.0e3,levels=[levels[contour_idx],],colors='w', linewidths=4.0) a=area(vs) R=(np.mean(vs[:,0])**2+np.mean(vs[:,1])**2)**(0.5) print "R = ", R sub_area=tr_f*tz_f print "Contour of value "+str(levels[contour_idx])+" has (roughly) A="+str(round(a,4)) print "V = "+str(round(2*np.pi*R*a,4)) + "m-3, " +str(round(2*np.pi*R*a,4)*1000) + " l" print "(lower estimate using Green's theorem)" print "Confinement volume: ", round(2*np.pi*R*a-sub_area,4) print "*****************" user_in=raw_input('Enter 1 to look at a different contour, or anything else to stop \n') if user_in=='1': user_req=1 else: user_req=0 print " - "*20
# objective Z = 100 * (Y - X**2)**2 + (1 - X)**2 # and the constraint contours A = X * Y B = X + Y**2 # plot the contours and constraints plt.figure() levels = [250, 500, 1000, 2000, 3000, 6000] CS = plt.contour(X, Y, Z, levels, colors="k") levels = np.arange(1.0, 1.01) CS1 = plt.contour(X, Y, A, levels, colors="g") levels = np.arange(0.0, 0.01) CS2 = plt.contour(X, Y, B, levels, colors="b") plt.clabel(CS, inline=1) plt.clabel(CS1, inline=1) plt.clabel(CS2, inline=1) # set the one sided variable xupper = [0.5, 0.5] yupper = [-7, 3.0] # Now plot the optimizer output styleList = ["ko-", "ro-", "bo-", "go-", "mo-", "co-", "ks--"] counter = 0 for opt in db.keys(): plt.plot(xuser[opt][:, 0], xuser[opt][:, 1], styleList[counter], label=opt) counter += 1 plt.plot(xupper, yupper, "k")
ax.set_ylabel('$\\theta_{2}$') ax.set_zlabel('$E_{in}(h)$') fig.colorbar(surf, shrink=0.5, aspect=5) plot.show() # Figure 6.2 V, U = np.gradient(Z, .2, .2) Q = plot.quiver(X, Y, -U, -V, pivot='mid', units='inches') plot.xlabel('$\\theta_{1}$') plot.ylabel('$\\theta_{2}$') plot.show() p = plot.contour(X, Y, Z, cmap='brg_r') plot.clabel(p, fontsize=9, inline=1) current_value = np.array([0, 0]) x_values = [0] y_values = [0] V, U = np.gradient(Z, .1, .1) steps = 1000 for i in range(0, steps): current_value = current_value - [ 0.1 * V[int(current_value[0] / 0.1), int(current_value[1] / 0.1)], 0.1 * U[int(current_value[0] / 0.1), int(current_value[1] / 0.1)] ] x_values.append(current_value[0]) y_values.append(current_value[1]) plot.plot(x_values, y_values, 'k:')
pl.ylabel(r'$-G(\ell,\theta)\,\,\mathrm{[k_{B}T]}$', size = 20) #pl.axis([1.5e-9, 6.5e-8,100,145]) pl.title(r'$\mathrm{-G(\ell,\theta)\,vs.\,separation:\,parallel,\,retarded,\,water}$', size = 20) #pl.legend(loc = 'best') pl.savefig('plots/par_ret_water/G_vs_l.pdf') show() #G_l_t_dt[G_l_t_dt>300]= np.nan #NOTE: remove me later #G_l_t_dt[G_l_t_dt<200e-25]= np.nan #NOTE: remove me later # CONTOUR PLOT: X,Y = np.meshgrid(thetas, ls) pl.figure() pl.contourf(X, Y, np.log(G_l_t_dt), 25)#, cmap = cm.hot()) CS = pl.contour(X,Y,np.log(G_l_t_dt))#, levels = np.linspace(1e-1,1e10,10)) pl.clabel(CS, inline =1,fmt = '%1.5f', fontsize = 18,color = 'k')#, manual = man_loc) pl.xlabel(r'$Angle\,\,\mathrm{[radians]}$', size = 20) pl.ylabel(r'$Separation\,\,\mathrm{[m]}$', size = 20) pl.title(r'$\mathrm{-Log(G),\,retarded,\,parallel\,cyls\,in\,water}$', size = 20)#uas a function of separation and angle') cbar = pl.colorbar(CS, shrink = 0.8, extend = 'both') cbar.ax.set_ylabel(r'$-Log(G(\mathcal{\ell},\theta))\,\,[k_{B}T]$', size = 14) cbar.add_lines(CS) ##pl.axis([0,1.0,0,1.0]) #pl.grid() pl.savefig('plots/par_ret_water/logG_contour.pdf') show() fig = pl.figure() ax = fig.gca(projection = '3d') #ax.text(-7, 6, 0.7, r'$\zeta/\omega_{0}$', zdir = (-1,1,-3), size = 21) surf = ax.plot_surface(X,Y, G_l_t_dt, rstride = 1, cstride = 1,alpha = 0.2, linewidth = 0.3)#edgecolor = 'none',antialiased = True, shade = False, norm = norm, linewidth = 0.3)
zul = z.max() plt.figure(1, figsize=(10, 10.0)) xi = np.linspace(xll, xul, N) yi = np.linspace(yll, yul, N) zi = scipy.interpolate.griddata((x, y), z, (xi[None, :], yi[:, None]), method='cubic') contours = plt.contour(xi, yi, zi, levels=(2.3, 6.18, 11.83), colors=('orange', 'red', 'violet')) plt.clabel(contours, inline=True, fontsize=14) image = plt.imshow(zi, extent=[xll, xul, yll, yul], origin='lower', aspect=(xul - xll) / (yul - yll), norm=mpl.colors.Normalize(vmin=0., vmax=12.), cmap=plt.cm.Blues_r) clb = plt.colorbar(image, fraction=0.045, pad=0.045, fontsize=14) plt.tick_params(axis='both', which='major', labelsize=16) plt.tick_params(axis='both', which='minor', labelsize=16) clb.set_label(r'$\chi^{2}}$', labelpad=-40, y=1.05, rotation=0, fontsize=18) plt.ylabel(r'$\delta_{CP}$ $\degree$', fontsize=20) plt.xlabel(r'$\theta_{13}$ $\degree$', fontsize=20) plt.title(r'$\delta_{CP}-\theta_{13}$', fontsize=22) plt.tight_layout() plt.savefig('theta13deltaCP.pdf')
np.linspace(0, 3.5, 200).reshape(-1, 1), ) X_new = np.c_[x0.ravel(), x1.ravel()] softmax_reg = LogisticRegression(multi_class="multinomial", solver="lbfgs", C=10, random_state=42) softmax_reg.fit(X, y) y_proba = softmax_reg.predict_proba(X_new) y_predict = softmax_reg.predict(X_new) zz1 = y_proba[:, 1].reshape(x0.shape) zz = y_predict.reshape(x0.shape) plt.figure(figsize=(10, 4)) plt.plot(X[y == 2, 0], X[y == 2, 1], "g^", label="Iris-Virginica") plt.plot(X[y == 1, 0], X[y == 1, 1], "bs", label="Iris-Versicolor") plt.plot(X[y == 0, 0], X[y == 0, 1], "yo", label="Iris-Setosa") custom_cmap = ListedColormap(['#fafab0', '#9898ff', '#a0faa0']) plt.contourf(x0, x1, zz, cmap=custom_cmap) contour = plt.contour(x0, x1, zz1, cmap=plt.cm.brg) plt.clabel(contour, inline=1, fontsize=12) plt.xlabel("Petal length", fontsize=14) plt.ylabel("Petal width", fontsize=14) plt.legend(loc="center left", fontsize=14) plt.axis([0, 7, 0, 3.5]) print("softmax_regression_contour_plot") plt.show()