def plots(saliency_map): """ Positive/Negative values mean that when occluding that pixel the prediction went down/up. Parameters ---------- saliency_map : np.array. shape(x,y) Saliency map to be plotted """ # Plot mask and original image fig, ax = plt.subplots(1,2, figsize=(12, 4)) cf = ax[0].imshow(saliency_map, clim=[np.amin(saliency_map), np.amax(saliency_map)]) fig.colorbar(cf, ax=ax[0], fraction=0.046, pad=0.04) ax[0].set_title('Saliency map') x,y = saliency_map.shape ori_patch = np.array(ori)[(X-x)/2:(X+x)/2, (Y-y)/2:(Y+y)/2] #central patch ax[1].imshow(ori_patch) ax[1].set_title('Original image') # Plot contour plots of the mask over the image plt.figure() plt.imshow(ori_patch) CS = plt.contour(np.arange(saliency_map.shape[0]), np.arange(saliency_map.shape[1]), saliency_map) plt.clabel(CS, inline=1, fontsize=10) plt.title('Contour plot') # Plot RGBA image (soft mask) plt.figure() saliency_map -= np.amin(saliency_map) saliency_map /= np.amax(saliency_map) alpha_channel = np.round(saliency_map*255) rgba_arr = np.dstack((ori_patch, alpha_channel)).astype(np.uint8) plt.imshow(rgba_arr) plt.title('RGBA image')
def plot_taylor_diagram(self): # fig = _plt.figure(figsize=(10, 4)) refstd = self._data.std(ddof = 1) samples = [[self._correlant.std(ddof = 1), self.pearson_r[0]],] # Taylor diagram dia = TaylorDiagram(refstd, # fig=fig, rect=111, label="Reference", srange=(0.5, 1.5)) colors = _plt.matplotlib.cm.jet(_np.linspace(0, 1, len(samples))) # Add the models to Taylor diagram for i, (stddev, corrcoef) in enumerate(samples): dia.add_sample(stddev, corrcoef, marker='$%d$' % (i+1), ms=10, ls='', mfc=colors[i], mec=colors[i], label="Model %d" % (i+1)) # Add grid dia.add_grid() # Add RMS contours, and label them contours = dia.add_contours(colors='0.5') _plt.clabel(contours, inline=1, fontsize=10, fmt='%.2f') # Add a figure legend dia.fig.legend(dia.samplePoints, [ p.get_label() for p in dia.samplePoints ], numpoints=1, prop=dict(size='small'), loc='upper right') return dia
def __hist2d(self, x, y, contour=False, bins=(200, 200), cmap="Purples", interpolation='nearest', origin="lower", colors="k"): """ Parameters ---------- bins : tuple of two ints """ H, xedges, yedges = np.histogram2d(x, y, bins) extent = [xedges.min(), xedges.max(), yedges.min(), yedges.max()] if not contour: plt.imshow(H, extent=extent, interpolation=interpolation, origin=origin, cmap=cmap, aspect="auto") # plt.colorbar(fontsize=4) else: CS = plt.contour(H, extent=extent, origin=origin, colors=colors) plt.clabel(CS, inline=1, fontsize=10)
def diffDensity(fig, F2, F3, Trange): T1 = copy.deepcopy(Trange) T2 = copy.deepcopy(Trange) X, Y = numpy.meshgrid(T1, T2) p2 = [] p3 = [] for tau in Trange: p2.append(F2.pdf(tau)) p3.append(F3.pdf(tau)) p2mat = numpy.matrix(p2) p3mat = numpy.matrix(p3) pp2 = p2mat.T * p2mat pp3 = p3mat.T * p3mat PXP = numpy.array(numpy.log(pp3) - numpy.log(pp2)) # norm = plt.cm.colors.Normalize(vmin=-0.8,vmax=0.8) levels = numpy.arange(-2.0, .1, .1) cmap = plt.cm.get_cmap("PiYG") cmap.set_under(color='red', alpha=0.3) cmap.set_over(color='red', alpha=0.3) cset = plt.contourf(X, Y, PXP, levels=numpy.array([-10.0, 0, .8]), colors=('r', 'g'), alpha=.3) #plt.cm.get_cmap(cmap,2)) matplotlib.rcParams['contour.negative_linestyle'] = 'solid' levels = numpy.arange(-10, .8, .1) cs2 = plt.contour(X, Y, PXP, levels=levels, colors='k', alpha=.2) plt.clabel(cs2, levels[91:], fontsize=9, inline=1) # plt.colorbar(cset) plt.xlabel("First Opening Time $\\tau_1$") plt.ylabel("Second Opening Time $\\tau_2$") plt.title( "Test Statistic Comparing Models as a Function of Two Observations") plt.show()
def countour_plot(dataDist, range_min=-1, range_max=3, delta=0.025): x = y = np.arange(range_min, range_max, delta) X, Y = np.meshgrid(x, y) Z = X.copy() for i in range(X.shape[0]): for j in range(X.shape[1]): Z[i, j] = dataDist.pdf([X[i, j], Y[i, j]]) plt.figure() CS = plt.contour(X, Y, Z) plt.clabel(CS, inline=1, fontsize=10)
def visualize_GD(): ''' Created on Oct 28, 2010 @author: Peter ''' import matplotlib import numpy as np import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.pyplot as plt leafNode = dict(boxstyle="round4", fc="0.8") arrow_args = dict(arrowstyle="<-") matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'out' delta = 0.025 x = np.arange(-2.0, 2.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) Z1 = -((X-1)**2) Z2 = -(Y**2) #Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) #Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) # difference of Gaussians Z = 1.0 * (Z2 + Z1)+5.0 # 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(X, Y, Z) plt.annotate('', xy=(0.05, 0.05), xycoords='axes fraction', xytext=(0.2,0.2), textcoords='axes fraction', va="center", ha="center", bbox=leafNode, arrowprops=arrow_args ) plt.text(-1.9, -1.8, 'P0') plt.annotate('', xy=(0.2,0.2), xycoords='axes fraction', xytext=(0.35,0.3), textcoords='axes fraction', va="center", ha="center", bbox=leafNode, arrowprops=arrow_args ) plt.text(-1.35, -1.23, 'P1') plt.annotate('', xy=(0.35,0.3), xycoords='axes fraction', xytext=(0.45,0.35), textcoords='axes fraction', va="center", ha="center", bbox=leafNode, arrowprops=arrow_args ) plt.text(-0.7, -0.8, 'P2') plt.text(-0.3, -0.6, 'P3') plt.clabel(CS, inline=True, fontsize=10) plt.title('Gradient Ascent') plt.xlabel('x') plt.ylabel('y') plt.show()
def __hist2d(self,x,y,contour=False,bins=(200,200),cmap="Purples",interpolation='nearest',origin="lower", colors="k"): """ Parameters ---------- bins : tuple of two ints """ H, xedges, yedges = np.histogram2d(x, y, bins) extent = [xedges.min(), xedges.max(), yedges.min(), yedges.max()] if not contour: plt.imshow(H, extent=extent, interpolation=interpolation,origin=origin, cmap=cmap, aspect="auto") # plt.colorbar(fontsize=4) else: CS = plt.contour(H, extent=extent,origin=origin,colors=colors) plt.clabel(CS, inline=1, fontsize=10)
def initPlot(plotName, x1, x2): plt.figure(plotName) # Окрашивание допустимого множества D (желтый цвет) plt.pcolormesh(x1, x2, (g1([x1, x2]) <= 0) & (g2([x1, x2]) <= 0) & (g3([x1, x2]) <= 0), alpha=0.1) # Линии уровня целевой функции (последний аргумент - количество линий) contours = plt.contour(x1, x2, f([x1, x2]), 30) # Значение уровня на линиях (последний аргумент - размер шрифта) plt.clabel(contours, inline=True, fontsize=8) # Ограничения(предпоследний аргумент - активность ограничения, т.е. g1(x) = 0) plt.contour(x1, x2, g1([x1, x2]), (0,), colors='g') plt.contour(x1, x2, g2([x1, x2]), (0,), colors='r') plt.contour(x1, x2, g3([x1, x2]), (0,), colors='y') return plt
def contourplot(fun, xlim=[-0, 5, 0.5, 0.1], ylim=[-0.5, 0.5, 0.1], levels=np.arange(0, 4, 0.2), aspect1='False', xlabel='x (m)', ylabel="x'", ttl='Jordan form abs(b0) contour and tracking', cl='r', ls='solid'): matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'out' #print "xlim,ylim",xlim,ylim x = np.arange(xlim[0], xlim[1], xlim[2]) y = np.arange(ylim[0], ylim[1], ylim[2]) X, Y = np.meshgrid(x, y) # generate Z function height given the grid specified by X,Y # X,Y are the coordinates of the grid points, #X and Y have same array structure, rows are evenly spaced in y direction, columns for x Z = fun(X, Y) # 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(X, Y, Z, levels, colors=cl, linewidths=4, linestyles=ls) #CS = plt.contour(X, Y, Z, levels,colors=('r', 'green', 'blue', (1,1,0), '#afeeee', '0.2')) #CS = plt.contour(X, Y, Z, levels,colors='k') plt.clabel(CS, inline=1, fontsize=10) print "title=", ttl plt.title(ttl) plt.xlabel(xlabel) plt.ylabel(ylabel) if aspect1 == 'True': plt.axes().set_aspect('equal', 'datalim') plt.axis([ xlim[0], xlim[1], ylim[0], ylim[1], ]) #plt.show() return
def plot_image_contour(p, h, v, aspect='equal', title="", xtitle="", ytitle="", show=1): fig = plt.figure() # cmap = plt.cm.Greys plt.imshow(p.T, origin='lower', extent=[h[0], h[-1], v[0], v[-1]], cmap=None, aspect=aspect) if True: plt.colorbar() ax = fig.gca() ax.set_xlabel(xtitle) ax.set_ylabel(ytitle) plt.title(title) levels = numpy.arange( 0.0, p.max() * 0.95, 100.0) # Boost the upper limit to avoid truncation errors. vv = plt.axis() ff = plt.contour(p.T, levels, colors='k', origin='lower', extent=[h[0], h[-1], v[0], v[-1]]) plt.clabel(ff, fmt='%d', colors='b', fontsize=14) plt.axis(vv) if show: plt.show()
def plot_slice (xgrid,ygrid,vargrid,zval): levels=[0,1,2,3,4,5,6,7,8,9] slice_v=zval xdraw=xgrid[:,:,slice_v] ydraw=ygrid[:,:,slice_v] Vdraw=vargrid[:,:,slice_v] aa=plt.contourf(xdraw,ydraw,Vdraw,levels,apha=.75,cmap='jet') C=plt.contour(xdraw,ydraw,Vdraw, levels, colors='black', linewidth=.5) bb=plt.clabel(C, inline=1, fontsize=10) plt.colorbar(aa) #plt.show() return
def addContours(xv, yv, Z, levels=None, clabels=None, manual_locations=None): if levels is not None: cs = plt.contour(xv, yv, Z, levels=levels, colors='white') if clabels is None: clabels = levels fmt = {} for level in clabels: if level % 1 == 0: fmt[level] = "%1.0f" % level elif level * 10 % 1 == 0: fmt[level] = "%1.1f" % level elif level * 100 % 1 == 0: fmt[level] = "%1.2f" % level else: fmt[level] = "%1.3f" % level plt.clabel(cs, clabels, inline=1, color="white", fontsize=18, fmt=fmt, manual=manual_locations) # # add white rectangles under clabels # rect = Rectangle((10 * (24 * 60 * 60), 0.6), # 11 * (24 * 60 * 60), 0.8, # facecolor="white", # alpha=0.95, zorder=5) # ax = plt.gca() # ax.add_patch(rect) else: cs = plt.contour(xv, yv, Z, colors='white') plt.clabel(cs, inline=1, fmt="%1.2f", fontsize=18)
def scaling_plot(df, zcol, title, zdas=None, xcol='numIsilonNodes', xlabel=None, ycol='numPhysicalComputeNodes', ylabel=None): if xlabel == None: xlabel = xcol if ylabel == None: ylabel = ycol x = df[xcol].values y = df[ycol].values z = df[zcol].values # Set up a regular grid of interpolation points xi, yi = np.linspace(x.min(), x.max(), 100), np.linspace(y.min(), y.max(), 100) xi, yi = np.meshgrid(xi, yi) # Interpolate zi = scipy.interpolate.griddata((x, y), z, (xi, yi), method='cubic') fig = plt.figure(title) fig.clf() plt.set_cmap(cm.jet) plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower', extent=[x.min(), x.max(), y.min(), y.max()], aspect='auto') # Draw circles on actual measurement points plt.scatter(x, y, c=z) plt.colorbar() CS = plt.contour(xi, yi, zi, colors='k') plt.clabel(CS, inline=1, fontsize=10, fmt='%1.0f') if zdas is not None: dasNodes = np.arange(df.numPhysicalComputeNodes.min(), 2 * df.numPhysicalComputeNodes.max() + 1) dasZ = zdas * dasNodes CS = plt.contour(xi, yi, zi, colors='k', linestyles='dashed', levels=dasZ) fmtdict = {x[1]: 'DAS ' + str(int(x[0])) for x in zip(dasNodes, dasZ)} plt.clabel(CS, inline=1, fontsize=10, fmt=fmtdict) plt.title(title) plt.ylabel(ylabel) plt.xlabel(xlabel) plt.show()
#radmc3dPy.image.plotImage(imag,au=True,dpc=240.,log=True,maxlog=5,cmap='afmhot') radmc3dPy.image.plotImage(imag,au=True,dpc=240.,log=True,vmin=-10,vmax=-3,cmap='CMRmap',bunit='snu') #plb.savefig('figure+e6pho.eps', bbox_inches='tight') #plb.savefig("/Users/cagurto/Documents/Newradmc3d/version_0.39/python/model-py/figure1.png") plb.clf() # 2D TEMPERATURE CONTOUR (natconst.au=1.496e13) data = radmc3dPy.analyze.readData(dtemp=True) c = plb.contourf(data.grid.x/natconst.au, np.pi/2.-data.grid.y, data.dusttemp[:,:,0,0].T, 30) plb.xlabel('r [AU]') plb.ylabel(r'$\pi/2-\theta$') plb.xscale('log') cb = plb.colorbar(c) cb.set_label('T [K]', rotation=270.) c = plb.contour(data.grid.x/natconst.au, np.pi/2.-data.grid.y, data.dusttemp[:,:,0,0].T, 10, colors='k',linestyles='solid') plb.clabel(c, inline=1, fontsize=10) #plb.savefig('figure2Dtempcontour.eps', bbox_inches='tight') plb.show() # Dust density contours data = radmc3dPy.analyze.readData(ddens=True) c2 = plb.contourf(data.grid.x/natconst.au, np.pi/2.-data.grid.y, np.log10(data.rhodust[:,:,0,0].T), 30) plb.xlabel('r [AU]') plb.ylabel(r'$\pi/2-\theta$') plb.xscale('log') cb = plb.colorbar(c2) cb.set_label(r'$\log_{10}{\rho}$', rotation=270.) #plb.savefig('figure-dustdesnity.eps', bbox_inches='tight') plb.show()
def plot_chi2(model, data, fit_result=None, limits=None, disregard_correlation=False, npoints=(100, 100), stddev_max=3, fmt='%d', linewidth=2): """Plot chi**2 contours and linear fit approxiation Note that chi**2 is related to likelihood in the following way: L = exp(-(1/2)*chi**2) This means that log(L) and chi**2 are identical up to a factor (-2). """ import matplotlib.pylab as plt # Unpack model and fit result f, p, c = model # popt, pcov if disregard_correlation: fit_result[1] = set_off_diagonal_to_zero(fit_result[1]) # If no limits are given, compute a good choice from fit_result # Set up a grid of points in parameter space p1_lim = limits[0] p2_lim = limits[1] p1 = np.linspace(p1_lim[0], p1_lim[1], npoints[0]) p2 = np.linspace(p2_lim[0], p2_lim[1], npoints[1]) P1, P2 = plt.meshgrid(p1, p2) # Compute chi**2 (called chi2) for each grid point # Looping can probably be avoided, but I don't know how. x2 = np.empty_like(P1) # real chi**2 x2lin = np.empty_like(P1) # linear chi**2 approximation for i1 in range(p1.size): for i2 in range(p2.size): # Note the weird numpy indexing order. # i2,i1 seems wrong, but is correct: # TODO: implement pass # x2 [i2, i1] = chi2 ((p1[i1], p2[i2]), c, f, data) # x2lin[i2, i1] = chi2_lin((p1[i1], p2[i2]), fit_result) # Set the most likely point to chi**2 = 0 x2 -= x2.min() # Use sqrt scale # x2 = np.sqrt(x2) # x2lin = np.sqrt(x2lin) # Plot likelihood as color landscape x2_image = plt.pcolor(P1, P2, x2, vmin=0, vmax=stddev_max ** 2, cmap='gray') plt.colorbar() # Add marker at the minimum plt.plot(fit_result[0][0], fit_result[0][1], marker='*', markersize=12, color='r') # Add contour of real likelihood contour_levels = np.arange(1, stddev_max + 1) ** 2 x2_cont = plt.contour(P1, P2, x2, contour_levels, colors='r', linewidths=linewidth) plt.clabel(x2_cont, inline=1, fontsize=10, linewidths=linewidth, fmt=fmt) # Overplot linear approximation as contours x2lin_cont = plt.contour(P1, P2, x2lin, contour_levels, colors='b', linewidths=linewidth) plt.clabel(x2lin_cont, inline=1, fontsize=10, linewidths=linewidth, fmt=fmt) # Add colorbar and labels # axcb = plt.colorbar() # axcb.set_label(r'$\chi^2$', size=15) plt.xlabel('Parameter P1') plt.ylabel('Parameter P2') plt.axis(p1_lim + p2_lim)
if __name__ == '__main__': solver = PolicyIterationSolver() for ii in range(4): solver.policy_evaluation() solver.policy_update() print(solver.policy) import matplotlib.pylab as plt plt.subplot(121) CS = plt.contour(solver.policy, levels=range(-6, 6)) plt.clabel(CS) plt.xlim([0, 20]) plt.ylim([0, 20]) plt.axis('equal') plt.xticks(range(21)) plt.yticks(range(21)) plt.grid('on') plt.subplot(122) plt.pcolor(solver.value) plt.colorbar() plt.axis('equal') plt.show()
def decisionSurface(classifier, fileName=None, **args): global data global numpy_container classifier.train(data) numContours = 3 if 'numContours' in args: numContours = args['numContours'] title = None if 'title' in args: title = args['title'] markersize = 5 fontsize = 'medium' if 'markersize' in args: markersize = args['markersize'] if 'fontsize' in args: fontsize = args['fontsize'] contourFontsize = 10 if 'contourFontsize' in args: contourFontsize = args['contourFontsize'] showColorbar = False if 'showColorbar' in args: showColorbar = args['showColorbar'] show = True if fileName is not None: show = False if 'show' in args: show = args['show'] # setting up the grid delta = 0.01 if 'delta' in args: delta = args['delta'] x = arange(xmin, xmax, delta) y = arange(ymin, ymax, delta) Z = numpy.zeros((len(x), len(y)), numpy.float) gridX = numpy.zeros((len(x) * len(y), 2), numpy.float) n = 0 for i in range(len(x)): for j in range(len(y)): gridX[n][0] = x[i] gridX[n][1] = y[j] n += 1 if not numpy_container: gridData = VectorDataSet(gridX) gridData.attachKernel(data.kernel) else: gridData = PyVectorDataSet(gridX) results = classifier.test(gridData) n = 0 for i in range(len(x)): for j in range(len(y)): Z[i][j] = results.decisionFunc[n] n += 1 #pylab.figure() im = pylab.imshow(numpy.transpose(Z), interpolation='bilinear', origin='lower', cmap=pylab.cm.gray, extent=(xmin, xmax, ymin, ymax)) if numContours == 1: C = pylab.contour(numpy.transpose(Z), [0], origin='lower', linewidths=(3), colors='black', extent=(xmin, xmax, ymin, ymax)) elif numContours == 3: C = pylab.contour(numpy.transpose(Z), [-1, 0, 1], origin='lower', linewidths=(1, 3, 1), colors='black', extent=(xmin, xmax, ymin, ymax)) else: C = pylab.contour(numpy.transpose(Z), numContours, origin='lower', linewidths=2, extent=(xmin, xmax, ymin, ymax)) pylab.clabel(C, inline=1, fmt='%1.1f', fontsize=contourFontsize) # plot the data scatter(data, markersize=markersize) xticklabels = pylab.getp(pylab.gca(), 'xticklabels') yticklabels = pylab.getp(pylab.gca(), 'yticklabels') pylab.setp(xticklabels, fontsize=fontsize) pylab.setp(yticklabels, fontsize=fontsize) if title is not None: pylab.title(title, fontsize=fontsize) if showColorbar: pylab.colorbar(im) # colormap: pylab.hot() if fileName is not None: pylab.savefig(fileName) if show: pylab.show()
def visualize_GD(): ''' Created on Oct 28, 2010 @author: Peter ''' import matplotlib import numpy as np import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.pyplot as plt leafNode = dict(boxstyle="round4", fc="0.8") arrow_args = dict(arrowstyle="<-") matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'out' delta = 0.025 x = np.arange(-2.0, 2.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) Z1 = -((X - 1)**2) Z2 = -(Y**2) #Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) #Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) # difference of Gaussians Z = 1.0 * (Z2 + Z1) + 5.0 # 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(X, Y, Z) plt.annotate('', xy=(0.05, 0.05), xycoords='axes fraction', xytext=(0.2, 0.2), textcoords='axes fraction', va="center", ha="center", bbox=leafNode, arrowprops=arrow_args) plt.text(-1.9, -1.8, 'P0') plt.annotate('', xy=(0.2, 0.2), xycoords='axes fraction', xytext=(0.35, 0.3), textcoords='axes fraction', va="center", ha="center", bbox=leafNode, arrowprops=arrow_args) plt.text(-1.35, -1.23, 'P1') plt.annotate('', xy=(0.35, 0.3), xycoords='axes fraction', xytext=(0.45, 0.35), textcoords='axes fraction', va="center", ha="center", bbox=leafNode, arrowprops=arrow_args) plt.text(-0.7, -0.8, 'P2') plt.text(-0.3, -0.6, 'P3') plt.clabel(CS, inline=True, fontsize=10) plt.title('Gradient Ascent') plt.xlabel('x') plt.ylabel('y') plt.show()
elapsed_time += dt #plotting #if t[i] % tplot == 0: #plot stuff #current_time=t[i] # get a 2D array version of the water height zwR = mg.node_vector_to_raster(zw) # create raster image #plt.close() image_extent = [0,num_cols*dx,0,num_rows*dx] im = plt.imshow(zwR,cmap=plt.cm.RdBu,extent=image_extent) plt.xlabel('Distance (m)', fontsize=12) plt.ylabel('Distance (m)', fontsize=12) # create contours cset = plt.contour(zwR,extent=image_extent) plt.clabel(cset,inline=True, fmt='%1.1f', fontsize=10) # color bar on side cb = plt.colorbar(im) cb.set_label('Water Elevation (m)', fontsize=12) # add title plt.title('Water Elevation') # Save plot #plt.savefig('Water_Elevation') # Display plot plt.pause(0.1) #else: #pass
def plot_quantity(self, type='gasdensity', plotfile=None, vmax=None, vmin=None, length_unit='au', dens_unit='number', xlim=None, xlog=False, ylog=False, ylim=None, nlevels=50, curves=None, isotropic=False, colors=None, linestyles=None, zoverr=False, clabels=False): if length_unit is 'au': scale_length = self.au if type is 'gasdensity': clabel = 'Gas density [$g/cm^3$]' quantity = self.gasdensity if dens_unit is 'number': scale_dens = self.molweight quantity /= scale_dens clabel = 'Gas density [$cm^{-3}$]' if type is 'abundance_H': clabel = 'Abundance [H$^{-1}$]' quantity = self.abundance / 2.0 if type is 'abundance': clabel = 'Abundance [H${_2}^{-1}$]' quantity = self.abundance if type is 'dusttemperature': clabel = 'Dust temperature [K]' quantity = self.dusttemperature[:, :, 0] if type is 'gastemperature': clabel = 'Gas temperature [K]' self.gastemperature[self.abundance < 1e-30] = np.nan quantity = self.gastemperature if vmax is None: vmax = np.max(quantity) if vmin is None: vmin = np.min(quantity) if plotfile is None: plotfile = type + '.pdf' fig = plt.figure() ax = fig.add_subplot(111) ax.set_xlabel('Disk radius [AU]') if zoverr: ax.set_ylabel('Z/R') else: ax.set_ylabel('Disk height [AU]') levels = np.linspace(np.log10(vmin), np.log10(vmax), nlevels) # Plot as z/r? if zoverr: xx = self.x / scale_length yy = self.y / self.x else: xx = self.x / scale_length yy = self.y / scale_length fc = ax.contourf(xx,yy,np.log10(quantity),levels=levels,\ extend='both',cmap=plt.cm.magma,aspect='equal') if xlim is not None: ax.set_xlim(xlim) if ylim is not None: ax.set_ylim(ylim) if xlog: ax.set_xscale('log') if ylog: ax.set_yscale('log') if isotropic: ax.set_aspect('equal') if curves is not None: if colors is None: ncurves = len(curves) colors = ['darkred'] * ncurves if linestyles is None: nl = len(curves) linestyles = ['-'] * nl for curve, color, linestyle in zip(curves, colors, linestyles): if zoverr: ax.plot(curve[0], curve[1] / curve[0], lw=2., color=color, linestyle=linestyle) else: ax.plot(curve[0], curve[1], lw=2., color=color, linestyle=linestyle) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="3%", pad=0.1) fig.colorbar(fc, orientation='vertical', cax=cax, label=clabel, format=ticker.FuncFormatter(cbfmt)) if clabels: fig.show() fc.levels = 10**fc.levels plt.clabel(fc, fc.levels, inline=False, colors='black', use_clabeltext=True, manual=True, fmt='%4.0f') fig.tight_layout() fig.savefig(plotfile)
"""Эта часть отделяет допустимую область (та что не в сетке)""" x1_, x2_ = np.meshgrid(np.linspace(-1.5, 2.0, 500), np.linspace(-2.0, 2.0, 500)) """Уравнение с листочка""" f_ = 20 * (np.cos(3 * x1_) - x2_) ** 2 + (x2_ - 4 * x1_) ** 2 """Ограничения g1,g2,g3""" g1_ = x2_ + x1_ - 0.1 g2_ = x2_ - x1_ - 0.25 g3_ = -1 * (x1_ - 1) ** 2 - 2 * (x2_ - 1) ** 2 + 5 plt.figure() plt.pcolormesh(x1_, x2_, (g1_ <= 0) & (g2_ <= 0) & (g3_ <= 0), alpha=0.1) contours = plt.contour(x1_, x2_, f_, 25) plt.clabel(contours, inline=True, fontsize=8) contours = plt.contour(x1_, x2_, g1_, (0,), colors="r") contours = plt.contour(x1_, x2_, g2_, (0,), colors="y") contours = plt.contour(x1_, x2_, g3_, (0,), colors="g") """Первое приближение, можно понять по картинке куда сходятся линии""" initial_guess = numpy.array([1.1, -1.2]) plt.scatter(initial_guess[0], initial_guess[1], color="r") """Уравнения огрниченний где параметр вектор""" def con_g1(x): return x[0] + x[1] - 0.1
for [x1, y1] in vs[1:]: dx = x1 - x0 dy = y1 - y0 a += 0.5 * (y0 * dx - x0 * dy) x0 = x1 y0 = y1 return a # Generate some test data. delta = 0.01 x = np.arange(-3.1, 3.1, delta) y = np.arange(-3.1, 3.1, delta) X, Y = np.meshgrid(x, y) r = np.sqrt(X**2 + Y**2) # Plot the data levels = [1.0, 2.0, 3.0] cs = plt.contour(X, Y, r, levels=levels) plt.clabel(cs, inline=1, fontsize=10) # Get one of the contours from the plot. for i in range(len(levels)): contour = cs.collections[i] vs = contour.get_paths()[0].vertices # Compute area enclosed by vertices. a = area(vs) print("r = " + str(levels[i]) + ": a =" + str(a)) plt.show()
['record/v2/numerical/NonConvex_SGD_0.03.json', 'SGD'], ['record/v2/numerical/NonConvex_ARMAGD_0.03_[0, 0.9].json', 'FGD-AR(1)'], ['record/v2/numerical/NonConvex_ARMAGD_0.03_[0.1, 0.8].json', 'FGD-AR(2)'], ['record/v2/numerical/NonConvex_MASGD_0.03_[0.0, 0.9].json', 'FGD-MA(1)'], ['record/v2/numerical/NonConvex_MASGD_0.03_[0.1, 0.8].json', 'FGD-MA(2)'] ] x = arange(-6.0, 6.1, 0.1) y = arange(-6.0, 6.1, 0.1) X, Y = np.meshgrid(x, y, sparse=True) # grid of point Z = z_func(X, Y) # evaluation of the function on the grid im = imshow(Z, extent=[-6, 6, -6, 6], cmap=cm.RdBu) # drawing the function # im = pylab.contourf(x, y, Z, cmap=cm.RdBu) # adding the Contour lines with labels cset = contour(x, y, Z, linewidths=1, cmap=cm.Set2) clabel(cset, inline=True, fmt='%1.1f', fontsize=10) colorbar(im) # adding the colobar on the right # for item in record: # with open(item[0], "r") as read_file: # data = json.load(read_file) # X = np.array(data['x']) # Y = np.array(data['y']) # # pylab.plot(X, Y, label=item[1], alpha=0.8) pylab.xlabel('x') pylab.ylabel('y') pylab.xlim(-6, 6) pylab.ylim(-6, 6) # pylab.legend()
def plot_compressor(mapname, maptype, mapdata, scaled_map, scalars, overlay, axes, filled, show_lines, Vspd, Veff): # ========================================================================== # each compressor plot consists of the following elements based on map type: # BETA RLINE # a regular plot of beta lines speed lines # a contour plot of efficiency efficiency # a contour plot of speed lines R lines # a scatter plot of op. points op. points # ========================================================================== WC=[] PR=[] EFF=[] NC=[] RL=[] # determination of maximum number of j values numJ=[] for i in range( 0,len( mapdata[alpha] ) ): numJ.append( len(mapdata[alpha][i]) ) maxJ = max( numJ ) # for each alpha value, create PYTHON arrays used for plotting for i in range( 0,len( mapdata[alpha] ) ): w=[] # array of speed values or Rline values x=[] # array of corrected flow values y=[] # array of PR values z=[] # array of efficiency values for j in range( 0,len( mapdata[alpha][i] ) ): if scaled_map == 1: w.append( mapdata[alpha][i][j][2]*scalars[3] ) x.append( mapdata[alpha][i][j][3]*scalars[0] ) y.append(( mapdata[alpha][i][j][4]-1.)*scalars[1] + 1. ) z.append( mapdata[alpha][i][j][5]*scalars[2] ) else: w.append( mapdata[alpha][i][j][2] ) x.append( mapdata[alpha][i][j][3] ) y.append( mapdata[alpha][i][j][4] ) z.append( mapdata[alpha][i][j][5] ) # if original map data is non-square, add duplicate data if len( mapdata[alpha][i] ) != maxJ: print "WARNING: for ", mapname, \ ": map data list is not square, adding data." for xtra in range( 0, maxJ-len( mapdata[alpha][i] ) ): if scaled_map == 1: w.append( mapdata[alpha][i][j][2]*scalars[3] ) x.append( mapdata[alpha][i][j][3]*scalars[0] ) y.append(( mapdata[alpha][i][j][4]-1.)*scalars[1] + 1. ) z.append( mapdata[alpha][i][j][5]*scalars[2] ) else: w.append( mapdata[alpha][i][j][2] ) x.append( mapdata[alpha][i][j][3] ) y.append( mapdata[alpha][i][j][4] ) z.append( mapdata[alpha][i][j][5] ) WC.append(x) PR.append(y) EFF.append(z) if maptype == 'BETA': NC.append(w) if maptype == 'RLINE': RL.append(w) # PLOT BETA LINES OR SPEED LINES if maptype == 'BETA': if show_lines == 1: if overlay == 0: pylab.plot( x, y, linewidth=0.5, linestyle = '--', color=linecolors[0] ) pylab.text( x[len(x)-1], y[len(y)-1], 'beta '+str( mapdata[alpha][i][j][1] ), ha='left', va='bottom', fontsize='8', color='red', rotation=35 ) else: pylab.plot( x, y, linewidth=0.5, linestyle = '--', color=linecolors[alpha] ) if maptype == 'RLINE': if overlay == 0: pylab.plot( x, y, color='blue' ) #pylab.text( x[0], y[0], #'speed '+str(mapdata[alpha][i][j][1]), ha='right', va='bottom', #fontsize='8', color='blue', rotation=-35 ) else: pylab.plot( x, y, color=linecolors[alpha] ) # turn these arrays into numpy arrays WC=np.array(WC) PR=np.array(PR) EFF=np.array(EFF) NC=np.array(NC) RL=np.array(RL) levels = [.5, .55, .6, .65, .7, .75, .8, .85, .9, .95, 1] if overlay == 0: # PLOT EFFICIENCY CONTOURS ONLY ON NON-OVERLAID MAPS if Veff != []: if filled == 0: pylab.contour(WC,PR,EFF,Veff,levels) cb = pylab.colorbar(ticks=Veff) cb.ax.set_ylabel('Veff') else: pylab.contourf(WC,PR,EFF,Veff,levels) cb = pylab.colorbar(ticks=Veff) cb.ax.set_ylabel('Veff') else: if filled == 0: pylab.contour(WC,PR,EFF,levels) cb = pylab.colorbar() cb.ax.set_ylabel('Eff') else: pylab.contourf(WC,PR,EFF,levels) cb = pylab.colorbar() cb.ax.set_ylabel('Eff') # PLOT SPEED CONTOURS FOR BETA MAPS if maptype == 'BETA': if Vspd != []: CS = pylab.contour(WC,PR,NC,Vspd,colors='blue') pylab.clabel(CS,Vspd,colors='blue',fmt='%3.0f') else: pylab.contour(WC,PR,NC,levels,colors='blue') # PLOT RLINE CONTOURS FOR RLINE MAPS if maptype == 'RLINE' and show_lines == 1: if Vspd != []: CS = pylab.contour(WC,PR,RL,Vspd, linewidths=0.5, colors='green') pylab.clabel(CS,Vspd,colors='green',fmt='%1.2f') else: pylab.contour(WC,PR,RL,levels,linewidths=0.5, colors='green') else: # PLOT SPEED CONTOURS FOR BETA MAPS if maptype == 'BETA': if Vspd != []: CS = pylab.contour(WC,PR,NC,Vspd,colors=linecolors[alpha]) pylab.clabel(CS,Vspd,colors=linecolors[alpha],fmt='%3.0f') else: pylab.contour(WC,PR,NC,levels,colors=linecolors[alpha]) # PLOT RLINE CONTOURS FOR RLINE MAPS if maptype == 'RLINE' and show_lines == 1: if Vspd != []: CS = pylab.contour(WC,PR,RL,Vspd,colors=linecolors[alpha]) pylab.clabel(CS,Vspd,colors=linecolors[alpha],fmt='%1.2f') else: pylab.contour(WC,PR,RL,levels,colors=linecolors[alpha]) ''' # PLOT THE OPERATING POINTS pntx=[] # array of corrected flow values for all of the saved points pnty=[] # array of PR values for all of the saved points for p in range(0,len(points_data)): pntx.append( points_data[p][component][4] ) pnty.append( points_data[p][component][5] ) # Seidel attempt at Operating Point data labels for p in range(0,len(points_data)): pointlabel= points_data[p][component][1] if (p/4.) == int(p/4.): yfact=1.08 pylab.text( pntx[p], pnty[p]*yfact, pointlabel, fontsize='8', color='black', rotation=0 ) pylab.plot( pntx[p], pnty[p], 'ks' , ms=4.0 ) elif (p/3.) == int(p/3.): yfact=1.04 pylab.text( pntx[p], pnty[p]*yfact, pointlabel, fontsize='8', color='blue', rotation=0 ) pylab.plot( pntx[p], pnty[p], 'bs' , ms=4.0 ) elif (p/2.) == int(p/2.): yfact=0.96 pylab.text( pntx[p], pnty[p]*yfact, pointlabel, fontsize='8', color='green', rotation=0 ) pylab.plot( pntx[p], pnty[p], 'gs' , ms=4.0 ) else: yfact=0.92 pylab.text( pntx[p], pnty[p]*yfact, pointlabel, fontsize='8', color='white', rotation=0 ) pylab.plot( pntx[p], pnty[p], 'ws' , ms=4.0 ) ''' # SET PLOT AXES IF SUPPLIED, LABEL AXES AND TITLE if axes != []: pylab.axis( axes ) pylab.xlabel('Wcorr') pylab.ylabel('PR') if multiple_alphas == 1 and overlay == 1: pylab.title( mapname + ' MAP: alpha = all' ) else: pylab.title( mapname + ' MAP: alpha = ' + \ str( mapdata[alpha][0][0][0] ) )
m.drawparallels(np.arange(-90, 90, 30), labels=[0, 0, 0, 0]) m.drawmeridians(np.arange(-120, 120 + 60, 60), labels=[0, 0, 0, 0]) cbar = plt.colorbar(orientation='horizontal', pad=0.03) cbar.set_label('pot. temp. bias [K]', fontsize=32) cbar.ax.tick_params(labelsize=32) # three contours #CS2 = plt.contour(x, y, zz_sigma_1[0,:,:], levels=np.arange(31.6,32.0+0.1,0.2),colors=['0.6','k','0.6']) CS2 = plt.contour(x, y, zz_sigma_1[0, :, :], levels=np.arange(31.8, 31.8 + 0.1, 0.2), colors=['k']) plt.clabel(CS2, fmt='%2.1f', colors='k', fontsize=0) # add contour line for easier understanding ## add MLD mean #levels = [100.] #np.arange(200., 200.+100., 100.) #MLD0=plt.contour(x, y, zz_MLDmean, levels = levels, \ # colors=['g'],linewidths=4, alpha=0.2) #alpha=0.2 #plt.clabel(MLD0, fmt='%2.1f', inline=False, colors='k', fontsize=0) ## add max MLD #levels = [500.] #np.arange(200., 200.+100., 100.) #MLD1=plt.contour(x, y, zz_MLDmax, levels = levels, \ # colors=['g'],linewidths=4) #alpha=0.2 #plt.clabel(MLD1, fmt='%2.1f', inline=False, colors='k', fontsize=0) plt.tight_layout() #plt.show()
def conto_plots(Data,DataMHD,**kwargs): Qu = jana.quantities() Cur = Qu.Current(Data) CurMHD = Qu.Current(DataMHD) Fastsp = Qu.Magspeed(Data)['fast'] Slowsp = Qu.Magspeed(Data)['slow'] Alfvsp = Qu.Magspeed(Data)['alfven'] Vpol = np.sqrt(Data.v1**2 + Data.v2**2) FastspMHD = Qu.Magspeed(DataMHD)['fast'] SlowspMHD = Qu.Magspeed(DataMHD)['slow'] AlfvspMHD = Qu.Magspeed(DataMHD)['alfven'] VpolMHD = np.sqrt(DataMHD.v1**2 + DataMHD.v2**2) fastrat = Fastsp/Vpol slowrat = Slowsp/Vpol Alfvrat = Alfvsp/Vpol fastratMHD = FastspMHD/VpolMHD slowratMHD = SlowspMHD/VpolMHD AlfvratMHD = AlfvspMHD/VpolMHD f1 = plt.figure(num=1) ax1 = f1.add_subplot(121) currcont=plt.contour(Data.x1,Data.x2,Cur.T,kwargs.get('Currents',[-0.7,-0.6,-0.5,-0.4,-0.3]),colors=kwargs.get('colors','r'),linestyles=kwargs.get('ls','-'),lw=kwargs.get('lw',2.0)) plt.clabel(currcont,manual=True) currmhdcont = plt.contour(DataMHD.x1,DataMHD.x2,CurMHD.T,kwargs.get('Currents',[-0.7,-0.6,-0.5,-0.4,-0.3]),colors=kwargs.get('colors','k'),linestyles=kwargs.get('ls','-'),lw=kwargs.get('lw',2.0)) plt.clabel(currmhdcont,manual=True) plt.xlabel(r'r [AU]') plt.ylabel(r'z [AU]') plt.title(r'Total Current -- $\int\int J_{z} r dr d\phi$') ax2 = f1.add_subplot(122) plt.xlabel(r'r [AU]') #plt.ylabel(r'$z [AU]$') plt.title(r'Critical Surfaces') fcont=plt.contour(Data.x1,Data.x2,fastrat.T,[1.0],colors='r',linestyles='solid') plt.clabel(fcont,inline=1,fmt=r'Fast') scont=plt.contour(Data.x1,Data.x2,slowrat.T,[1.0],colors='r',linestyles='dashdot') plt.clabel(scont,inline=1,fmt=r'Slow') acont=plt.contour(Data.x1,Data.x2,Alfvrat.T,[1.0],colors='r',linestyles='dashed') plt.clabel(acont,inline=1,fmt=r'Alfv$\acute{e}$n') mfcont=plt.contour(DataMHD.x1,DataMHD.x2,fastratMHD.T,[1.0],colors='k',linestyles='solid') plt.clabel(mfcont,manual=1,fmt=r'Fast') mscont=plt.contour(DataMHD.x1,DataMHD.x2,slowratMHD.T,[1.0],colors='k',linestyles='dashdot') plt.clabel(mscont,manual=1,fmt=r'Slow') macont=plt.contour(DataMHD.x1,DataMHD.x2,AlfvratMHD.T,[1.0],colors='k',linestyles='dashed') plt.clabel(macont,manual=1,fmt=r'Alfv$\acute{e}$n')
def plot(headobj, cbb, mf): # Imports import matplotlib.pyplot as plt delr = mf.dis.delr[0] delc = mf.dis.delc[0] nrow, ncol, nlay, nper = mf.nrow_ncol_nlay_nper Lx = delr * ncol Ly = delc * nrow # Setup contour parameters levels = np.linspace(0, 10, 11) extent = (delr / 2., Lx - delr / 2., delc / 2., Ly - delc / 2.) print('Levels: ', levels) print('Extent: ', extent) # Well point min_x, max_x, min_y, max_y = data.boundary.get_bounding_box(boundary_file)["bbox"] wpt = ((float(ncol / 2) - 0.5) * delr, (float(nrow / 2 - 1) + 0.5) * delc) print wpt # wpt = (450., 550.) # Make the plots mytimes = [1.0, 101.0, 201.0] for iplot, time in enumerate(mytimes): print('*****Processing time: ', time) head = headobj.get_data(totim=time) #Print statistics print('Head statistics') print(' min: ', head.min()) print(' max: ', head.max()) print(' std: ', head.std()) # Extract flow right face and flow front face frf = cbb.get_data(text='FLOW RIGHT FACE', totim=time)[0] fff = cbb.get_data(text='FLOW FRONT FACE', totim=time)[0] #Create the plot #plt.subplot(1, len(mytimes), iplot + 1, aspect='equal') plt.subplot(1, 1, 1, aspect='equal') plt.title('stress period ' + str(iplot + 1)) modelmap = flopy.plot.ModelMap(model=mf, layer=0) qm = modelmap.plot_ibound() lc = modelmap.plot_grid() qm = modelmap.plot_bc('GHB', alpha=0.5) cs = modelmap.contour_array(head, levels=levels) plt.clabel(cs, inline=1, fontsize=10, fmt='%1.1f', zorder=11) quiver = modelmap.plot_discharge(frf, fff, head=head) mfc = 'None' if (iplot+1) == len(mytimes): mfc='black' plt.plot(wpt[0], wpt[1], lw=0, marker='o', markersize=8, markeredgewidth=0.5, markeredgecolor='black', markerfacecolor=mfc, zorder=9) plt.text(wpt[0]+25, wpt[1]-25, 'well', size=12, zorder=12) plt.show() # Plot the head versus time idx = (0, nrow / 2 - 1, ncol / 2 - 1) ts = headobj.get_ts(idx) plt.subplot(1, 1, 1) ttl = 'Head at cell ({0},{1},{2})'.format(idx[0] + 1, idx[1] + 1, idx[2] + 1) plt.title(ttl) plt.xlabel('time') plt.ylabel('head') plt.plot(ts[:, 0], ts[:, 1]) plt.show()
""" Plot of wind speed, wind vectors and surface pressure By Richard Essery """ import numpy as np import matplotlib.pylab as plt plt.figure(figsize=(10, 10)) P = np.loadtxt('Psurf.txt') U = np.loadtxt('Uwind.txt') V = np.loadtxt('Vwind.txt') W = np.sqrt(U**2 + V**2) # wind speed as an image with a colour bar plt.imshow(W, cmap='PuBu', origin='lower') cbar = plt.colorbar(shrink=0.6) cbar.set_label('wind speed (m s$^{-1}$)', fontsize=16, rotation=270) # surface pressure as a contour plot with 4 hPa spacing levels = 960 + 4*np.arange(20) cs = plt.contour(P, colors='black', levels=levels) plt.clabel(cs, fmt='%d') # wind vectors plt.quiver(U,V) plt.xticks([]) plt.yticks([]) plt.show()
def comparar_gas_ideal(T, r="0", zoom=False): n = len(pairs) dq = np.zeros(Nreps * n, dtype=np.float32) dp = np.zeros(Nreps * n, dtype=np.float32) for i in range(Nreps): sim_q = np.random.random(3 * 1000) * L sim_p = np.random.normal(0, 1, 3 * 1000) * np.sqrt(m * T) * factor_p sim_q = np.array(sim_q, dtype=np.float32) sim_p = np.array(sim_p, dtype=np.float32) dq[n * i:n * (i + 1)], dp[n * i:n * (i + 1)] = deltas(sim_q, sim_p) plt.figure() counts, xbins, ybins, image = plt.hist2d(dq, dp, bins=200, norm=LogNorm(), cmap=plt.cm.rainbow) new_counts = scipy.ndimage.filters.gaussian_filter(counts, 1) plt.colorbar() CS = plt.contour(new_counts.transpose(), extent=[xbins[0], xbins[-1], ybins[0], ybins[-1]], linewidths=3, colors="black", levels=np.logspace(1, 2, 2)) plt.clabel(CS, colors="black", inline=True, fmt="%d", fontsize=20) plt.xlabel(r'$\Delta q$ [fm]', fontsize=14) plt.ylabel(r'$\Delta p$ [MeV/c]', fontsize=14) plt.title(r'Gas ideal - $\rho^*=%1.3f$ - $T=%1.4fMeV$' % (qo**3 * N / V, T), fontsize=16) plt.axis([0, np.sqrt(3) * L / 2, 0, 4000]) plt.grid() if (zoom): plt.axis([0, 4 * qo, 0, 4 * po * factor_p]) # DORSO rho = "rho" + r data = np.loadtxt(rho + "/histograma_2D_%f.txt" % T) xbins = data[0, 1:] ybins = data[1:, 0] counts = data[1:-1, 1:-1] Nbins_2D = len(xbins) - 1 dq = [] dp = [] for x in range(len(xbins) - 1): for y in range(len(ybins) - 1): for i in range(int(counts[x, y])): dq.append((xbins[x + 1] + xbins[x]) * 0.5) if (rho[0] != "M"): dp.append((ybins[y + 1] + ybins[y]) * 0.5 * factor_p) else: dp.append((ybins[y + 1] + ybins[y]) * 0.5) plt.figure() counts, xbins, ybins, image = plt.hist2d(dq, dp, bins=Nbins_2D, norm=LogNorm(), cmap=plt.cm.rainbow) new_counts = scipy.ndimage.filters.gaussian_filter(counts, 1) plt.colorbar() CS = plt.contour(new_counts.transpose(), extent=[xbins[0], xbins[-1], ybins[0], ybins[-1]], linewidths=3, colors="black", levels=np.logspace(1, 2, 2)) plt.clabel(CS, colors="black", inline=True, fmt="%d", fontsize=20) plt.xlabel(r'$\Delta q$ [fm]', fontsize=14) plt.ylabel(r'$\Delta p$ [MeV/c]', fontsize=14) plt.title(r'Dorso - $\rho^*=%1.3f$ - $T=%1.4fMeV$' % (qo**3 * N / V, T), fontsize=16) plt.axis([0, np.sqrt(3) * L / 2, 0, 4000]) plt.grid() if (zoom): plt.axis([0, 4 * qo, 0, 4 * po * factor_p]) plt.show() return dq, dp
mm = ax.contourf(lon2d,\ lat2d,\ data,\ vmin=-12,\ vmax=0, \ transform=ccrs.PlateCarree(),\ levels=data_levels,\ cmap=cmap0 ) data_contour = ax.contour(lon2d, lat2d, data, levels = data_levels, linewidths=2, colors='k', transform = ccrs.PlateCarree()) #Plot contour labels for the heights, leaving a break in the contours for the text (inline=True) plt.clabel(data_contour, data_levels, inline=True, fmt='%1i', fontsize=12) # Define gridline locations and draw the lines using cartopy's built-in gridliner: xticks = np.arange(-150.0,-40.0,20) yticks =np.arange(10,80,10) fig.canvas.draw() cbar = plt.colorbar(mm, shrink=0.75, drawedges='True', ticks=np.arange(-12, 0.1, 1.), extend='both') # 2018 cbar.ax.tick_params(labelsize=20) string_title=u'Température moyenne journalière du 1er novembre '+str(year-1)+' au '+ str(last_day) + ' mars '+str(year) plt.title(string_title, size='xx-large') plt.savefig('./figures_update/T2m_Mean_BV_'+str(year)+'.png', bbox_inches='tight', pad_inches=0.1) plt.show() plt.close()
dtype=np.float32) dq[i * p:(i + 1) * p], dp[i * p:(i + 1) * p] = deltas( q_temp, p_temp) counts, xbins, ybins, image = plt.hist2d(dq, dp, bins=100, norm=LogNorm(), cmap=plt.cm.rainbow) plt.colorbar() new_counts = scipy.ndimage.filters.gaussian_filter(counts, 1) CS = plt.contour(new_counts.transpose(), extent=[xbins[0], xbins[-1], ybins[0], ybins[-1]], linewidths=3, colors="black", levels=np.logspace(0, 2, 3)) plt.clabel(CS, colors="black", inline=True, fmt="%d", fontsize=20) plt.xlabel(r'$\Delta q$') plt.ylabel(r'$\Delta p$') plt.axis([0, xbins[-1], 0, ybins[-1]]) plt.title(r'$\rho=%1.4f fm^{-3}$' % (rhos[k])) plt.show() if (tipo == "gr"): seleccion = range(n_rhos) if (nargs >= 4): seleccion = [] for i in range(3, nargs): seleccion.append(int(sys.argv[i]))
ax.add_feature(cfeature.STATES, linewidth=.5) # Plot Height Contours clev500 = np.arange(5100, 6061, 60) cs = ax.contour(lon, lat, hght_500.m, clev500, colors='black', linewidths=1.0, linestyles='solid', transform=ccrs.PlateCarree()) plt.clabel(cs, fontsize=10, inline=1, inline_spacing=10, fmt='%i', rightside_up=True, use_clabeltext=True) # Plot Absolute Vorticity Contours clevvort500 = np.arange(-9, 50, 5) cs2 = ax.contour(lon, lat, avor * 10**5, clevvort500, colors='grey', linewidths=1.25, linestyles='dashed', transform=ccrs.PlateCarree()) plt.clabel(cs2,
import matplotlib.pylab as plt if __name__ == '__main__': A = np.array([[-1, 1], [0, -1]]) B = np.array([[-1, 5], [0, -2]]) print("Condition Number of A: {}".format(cond(A))) npts = 100 xmin, xmax = -3.0, 1.0 ymin, ymax = -2.0, 2.0 # x = np.arange(xmin, xmax, (xmax-xmin) / (npts-1)) # y = np.arange(ymin, ymax, (ymax-ymin) / (npts-1)) # X, Y = np.meshgrid(x, y) X, Y = np.meshgrid(np.linspace(xmin, xmax, npts), np.linspace(ymin, ymax, npts)) spectra_a, s_max = psa(A, X, Y, method='svd') spectra_b, s_max = psa(B, X, Y, method='svd') plt.xkcd() fig = plt.figure(figsize=(9, 4)) ax = fig.add_subplot(121) circles = np.logspace(np.log10(0.05), np.log10(2.1), 10)[:-3] CS = ax.contour(X, Y, spectra_a + 1e-20, levels=circles) plt.clabel(CS, inline=1, fontsize=10) ax = fig.add_subplot(122) CS = ax.contour(X, Y, spectra_b + 1e-20, levels=circles) plt.clabel(CS, inline=1, fontsize=10) plt.savefig('psuedo.pdf', axis='tight') plt.show()
fig = plt.figure() #2行2列的子图中的第一个,第一行的第一列 subfig1 = fig.add_subplot(2,2,1) #画等值线云图 surf1 = plt.contourf(X, Y, moni_block(moni_dict)) #添加色标 fig.colorbar(surf1) #添加标题 plt.title('contourf+colorbar') #d第二个子图,第一行的第二列 subfig2 = fig.add_subplot(2,2,2) #画等值线 surf2 = plt.contour(X, Y, moni_block(moni_dict)) #等值线上添加标记 plt.clabel(surf2, inline=1, fontsize=10, cmap='jet') #添加标题 plt.title('contour+clabel') #第三个子图,第二行的第一列 subfig3 = fig.add_subplot(2,2,3,projection='3d') #画三维边框 surf3 = subfig3.plot_wireframe(X, Y, moni_block(moni_dict), rstride=10, cstride=10, color = 'y') #画等值线 plt.contour(X, Y, f(X,Y)) #设置标题 plt.title('plot_wireframe+contour') #第四个子图,第二行的第二列 subfig4 = fig.add_subplot(2,2,4,projection='3d') #画三维图
def plot_chi2(model, data, fit_result=None, limits=None, disregard_correlation=False, npoints=(100, 100), stddev_max=3, fmt='%d', linewidth=2): """Plot chi**2 contours and linear fit approxiation Note that chi**2 is related to likelihood in the following way: L = exp(-(1/2)*chi**2) This means that log(L) and chi**2 are identical up to a factor (-2). """ import matplotlib.pylab as plt # Unpack model and fit result f, p, c = model # popt, pcov if disregard_correlation: fit_result[1] = set_off_diagonal_to_zero(fit_result[1]) # If no limits are given, compute a good choice from fit_result # Set up a grid of points in parameter space p1_lim = limits[0] p2_lim = limits[1] p1 = np.linspace(p1_lim[0], p1_lim[1], npoints[0]) p2 = np.linspace(p2_lim[0], p2_lim[1], npoints[1]) P1, P2 = plt.meshgrid(p1, p2) # Compute chi**2 (called chi2) for each grid point # Looping can probably be avoided, but I don't know how. x2 = np.empty_like(P1) # real chi**2 x2lin = np.empty_like(P1) # linear chi**2 approximation for i1 in range(p1.size): for i2 in range(p2.size): # Note the weird numpy indexing order. # i2,i1 seems wrong, but is correct: # TODO: implement pass # x2 [i2, i1] = chi2 ((p1[i1], p2[i2]), c, f, data) # x2lin[i2, i1] = chi2_lin((p1[i1], p2[i2]), fit_result) # Set the most likely point to chi**2 = 0 x2 -= x2.min() # Use sqrt scale # x2 = np.sqrt(x2) # x2lin = np.sqrt(x2lin) # Plot likelihood as color landscape x2_image = plt.pcolor(P1, P2, x2, vmin=0, vmax=stddev_max**2, cmap='gray') plt.colorbar() # Add marker at the minimum plt.plot(fit_result[0][0], fit_result[0][1], marker='*', markersize=12, color='r') # Add contour of real likelihood contour_levels = np.arange(1, stddev_max + 1)**2 x2_cont = plt.contour(P1, P2, x2, contour_levels, colors='r', linewidths=linewidth) plt.clabel(x2_cont, inline=1, fontsize=10, linewidths=linewidth, fmt=fmt) # Overplot linear approximation as contours x2lin_cont = plt.contour(P1, P2, x2lin, contour_levels, colors='b', linewidths=linewidth) plt.clabel(x2lin_cont, inline=1, fontsize=10, linewidths=linewidth, fmt=fmt) # Add colorbar and labels # axcb = plt.colorbar() # axcb.set_label(r'$\chi^2$', size=15) plt.xlabel('Parameter P1') plt.ylabel('Parameter P2') plt.axis(p1_lim + p2_lim)
def plot_HR(Ls=10**np.random.uniform(-5, 6, 200) * Lsun, Ts=np.random.uniform(0.25, 10, 200) * Tsun, Tmin=1000, Tmax=40000, Lmin=1e-5, Lmax=1e6): T, Mag = np.loadtxt('./data/stars.txt', usecols=[0, 1], unpack=True) L = Lsun * 10**(0.4 * (4.74 - Mag)) y, x = np.mgrid[np.log10(Lmin):np.log10(Lmax):100j, np.log10(Tmin):np.log10(Tmax):100j] size = np.sqrt(10**(y) * (Tsun / (10**x))**4) temp = x fig, ax = plt.subplots(figsize=(10, 12)) ax.set_ylim([y.min(), y.max()]) ax.set_xlim([x.min(), x.max()]) lgLsun = np.log10(1) lgTsun = np.log10(Tsun) lgL = np.log10(L / Lsun) lgT = np.log10(T) R = np.sqrt(10**(lgL) * (Tsun / (10**lgT))**4) lgLs = np.log10(Ls / Lsun) lgTs = np.log10(Ts) Rs = np.sqrt(10**(lgLs) * (Tsun / (10**lgTs))**4) levels = [0.001, 0.01, 0.1, 1, 10, 100, 1000] CS = ax.contour(x, y, size, colors='k', levels=levels) fmt = {} strs = [ str(levels[0]) + r' $R_{\odot}$ ', str(levels[1]) + r' $R_{\odot}$ ', str(levels[2]) + r' $R_{\odot}$ ', str(levels[3]) + r' $R_{\odot}$ ', str(levels[4]) + r' $R_{\odot}$ ', str(levels[5]) + r' $R_{\odot}$ ', str(levels[6]) + r' $R_{\odot}$ ' ] for l, s in zip(CS.levels, strs): fmt[l] = s plt.clabel(CS, inline=1, fmt=fmt, fontsize=10) s0 = 50 #size of sun ax.set_xlabel(r'surface temperature $T_{\star}$ [K]', fontsize=20) ax.set_ylabel(r'luminosity $L_{\star}$ [$L_{_\odot}$]', fontsize=20) ax.set_title('Hertzsprung-Russell diagram', fontsize=20) ax.scatter(lgT, lgL, s=R * s0, c=T, cmap='magma_r') ax.scatter(lgTs[0], lgLs[0], s=s0 * 4, color='green') ax.scatter(lgTs[0], lgLs[0], s=s0 * 4, color='goldenrod', marker=(5, 2)) ax.annotate("Object Nr. 1", (lgTs[0] + .1, lgLs[0] + .3), fontsize=18, color='green') ax.scatter(lgTs[1], lgLs[1], s=s0 * 4, color='red') ax.scatter(lgTs[1], lgLs[1], s=s0 * 4, color='goldenrod', marker=(5, 2)) ax.annotate("Object Nr. 2", (lgTs[1] + .1, lgLs[1] + .3), fontsize=18, color='red') ax.scatter(lgTs[2], lgLs[2], s=s0 * 4, color='blue') ax.scatter(lgTs[2], lgLs[2], s=s0 * 4, color='goldenrod', marker=(5, 2)) ax.annotate("Object Nr. 3", (lgTs[2] + .1, lgLs[2] + .3), fontsize=18, color='blue') #ax.scatter(lgTsun,lgLsun,c=T,s=s0,cmap='magma_r') def format_func_x(value, tick_number): # find number of multiples of pi/2 res = 10**value return r'{:0.0f}'.format(res) def format_func_y(value, tick_number): # find number of multiples of pi/2 res = 10**value return r'{:0.4f}'.format(res) ax.yaxis.set_major_formatter(plt.FuncFormatter(format_func_y)) ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func_x)) ax.invert_xaxis()
def decision_boundary_plot(svm, features, vectors, labels, kernel, fileName=None, **args): title = None if 'title' in args: title = args['title'] xlabel = None if 'xlabel' in args: xlabel = args['xlabel'] ylabel = None if 'ylabel' in args: ylabel = args['ylabel'] fontsize = 'medium' if 'fontsize' in args: fontsize = args['fontsize'] contourFontsize = 10 if 'contourFontsize' in args: contourFontsize = args['contourFontsize'] showColorbar = True if 'showColorbar' in args: showColorbar = args['showColorbar'] show = True if fileName is not None: show = False if 'show' in args: show = args['show'] # setting up the grid delta = 0.005 x = arange(xmin, xmax, delta) y = arange(ymin, ymax, delta) Z = numpy.zeros((len(x), len(y)), numpy.float_) gridX = numpy.zeros((len(x) * len(y), 2), numpy.float_) n = 0 for i in range(len(x)): for j in range(len(y)): gridX[n][0] = x[i] gridX[n][1] = y[j] n += 1 if kernel.get_name() == 'Linear' and 'customwandb' in args: kernel.init_optimization_svm(svm) b = svm.get_bias() w = kernel.get_w() kernel.set_w(args['customwandb'][0]) svm.set_bias(args['customwandb'][1]) if kernel.get_name() == 'Linear' and 'drawarrow' in args: kernel.init_optimization_svm(svm) b = svm.get_bias() w = kernel.get_w() s = 1.0 / numpy.dot(w, w) / 1.17 pylab.arrow(0, -b / w[1], w[0] * s, s * w[1], width=0.01, fc='#dddddd', ec='k') grid_features = RealFeatures(numpy.transpose(gridX)) results = svm_test(svm, kernel, features, grid_features) n = 0 for i in range(len(x)): for j in range(len(y)): Z[i][j] = results[n] n += 1 cdict = { 'red': ((0.0, 0.6, 0.6), (0.5, 0.8, 0.8), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.6, 0.6), (0.5, 0.8, 0.8), (1.0, 1.0, 1.0)), 'blue': ((0.0, 0.6, 0.6), (0.5, 0.8, 0.8), (1.0, 1.0, 1.0)), } my_cmap = matplotlib.colors.LinearSegmentedColormap( 'lightgray', cdict, 256) im = pylab.imshow(numpy.transpose(Z), interpolation='bilinear', origin='lower', cmap=my_cmap, extent=(xmin, xmax, ymin, ymax)) if 'decisionboundaryonly' in args: C1 = pylab.contour(numpy.transpose(Z), [0], origin='lower', linewidths=(3), colors=['k'], extent=(xmin, xmax, ymin, ymax)) else: C1 = pylab.contour(numpy.transpose(Z), [-1, 0, 1], origin='lower', linewidths=(1, 3, 1), colors=['k', 'k'], extent=(xmin, xmax, ymin, ymax)) pylab.clabel(C1, inline=1, fmt='%1.1f', fontsize=contourFontsize) # plot the data lab = labels.get_labels() vec = numpy.array(vectors) idx = numpy.where(lab == -1)[0] pylab.scatter(vec[idx, 0], vec[idx, 1], s=300, c='#4444ff', marker='o', alpha=0.8, zorder=100) idx = numpy.where(lab == +1)[0] pylab.scatter(vec[idx, 0], vec[idx, 1], s=500, c='#ff4444', marker='s', alpha=0.8, zorder=100) # plot SVs if not 'decisionboundaryonly' in args: training_outputs = svm_test(svm, kernel, features, features) sv_idx = numpy.where(abs(training_outputs) <= 1.01)[0] pylab.scatter(vec[sv_idx, 0], vec[sv_idx, 1], s=100, c='k', marker='o', alpha=0.8, zorder=100) if 'showmovedpoint' in args: x = -0.779838709677 y = -0.1375 pylab.scatter([x], [y], s=300, c='#4e4e61', marker='o', alpha=1, zorder=100, edgecolor='#454548') pylab.arrow(x, y - 0.1, 0, -0.8 / 1.5, width=0.01, fc='#dddddd', ec='k') #pylab.show() if title is not None: pylab.title(title, fontsize=fontsize) if ylabel: pylab.ylabel(ylabel, fontsize=fontsize) if xlabel: pylab.xlabel(xlabel, fontsize=fontsize) if showColorbar: pylab.colorbar(im) # colormap: pylab.hot() if fileName is not None: pylab.savefig(fileName) if show: pylab.show()
for j,r0 in enumerate(r0_array): # EVALUATION OF THE GRID OF THE LIKELIHOOD Jgrid[i,j] = Jfactor(D,np.inf,r0,rho0,0.5) # AND THE J-FACTOR Lgrid[i,j] = logLike(rho0*r0**3,j) #np.save('output/%s/Jgrid_%s'%(dwarf,dwarf),Jgrid) #np.save('output/%s/Lgrid_%s'%(dwarf,dwarf),Lgrid) log10Jrho1 = np.log10([Jfactor(D,np.inf,r0,1.,0.5) for r0 in r0_array]) def deltaJ(log10rho0,J,j): return abs(J-log10Jrho1[j]-2.*log10rho0) rho0star = np.empty([4]) r0star = np.empty([4]) for i,J in enumerate((15,16,18,20,21)): min_rho0J = sciopt.minimize_scalar(deltaJ,args=(J,59+i*2),tol=1.e-10) rho0star[i] = min_rho0J.x r0star[i] = r0_array[59+i*2] lplot = plt.pcolormesh(r0_array,rho0_array,Lgrid,shading='gouraud') ctJ = plt.contour(r0_array,rho0_array,np.log10(Jgrid),colors='k') ctL = plt.contour(r0_array,rho0_array,Lgrid,linestyles='dashed',colors='m') plt.scatter(r0star,np.power(10,rho0star),marker='*',c='w',s=100,edgecolor='w') plt.clabel(ctJ,inline=1,fmt='%1.0f',colors='k') plt.clabel(ctL,inline=1,fmt='%1.0f',colors='m') cx = plt.colorbar(lplot,pad=0) cx.set_label(r'-$log$Like$(\rho_0,r_0|\vec v,\vec \sigma_v)$',fontsize=14) plt.semilogy() plt.ylabel(r'$\rho_0 [M_\odot$ kpc$^{-3}$]',fontsize=14) plt.xlabel(r'$r_0$ [kpc]',fontsize=14) plt.suptitle('%s'%names[dwarf],fontsize=16) plt.show()
oc2 = lambda l0,lm,ld: (2*pi*C) * (1./(l0+lm+ld)) ocp = lambda l0,lm,ld: (2*pi*C) * (1./(l0-lm-ld)) ocs = lambda l0,lm,ld: (2*pi*C) * (1./(l0-lm+ld)) o1 = (2*pi*C) * (1./(l0+l_mean-l_delta)) o2 = (2*pi*C) * (1./(l0+l_mean+l_delta)) op = (2*pi*C) * (1./(l0-l_mean-l_delta)) os = (2*pi*C) * (1./(l0-l_mean+l_delta)) w_mean = l_mean *(2*pi*C) /l0**2 lm = linspace(5*nano,40*nano, 50) ld = linspace(1*nano, 5*nano, 50) Lm,Ld = meshgrid(lm,ld) d_beta_b = b2*(o1**2-o2**2+os**2-op**2) #d_beta = b2*((oc1(l0,Lm,Ld)**2-oc2(l0,Lm,Ld)**2+ocs(l0,Lm,Ld)**2-ocp(l0,Lm,Ld)**2)) d_beta = bb(l0+Lm+Ld)-bb(l0+Lm-Ld)+bb(l0-Lm+Ld)-bb(l0-Lm-Ld) d_beta_i = bb(l0+Lm)+bb(l0+Lm)-bb(l0-Lm)-bb(l0+2*Lm) pl.contourf(lm,ld, 1/d_beta*1e9) pl.clabel(pl.contour(lm,ld,d_beta/d_beta_i, linewidths = 3), fmt = '%3.2f', colors = 'k', fontsize=14) pl.show() ## Phasematching lenght print "Phasematching lenght %.4f nm"%(1/d_beta_b*1e9)
plt.axis('scaled') plt.subplot(2, 2, 2) plt.plot(r3, soln3.burntime, 'b.') plt.xlabel('distance') plt.ylabel('burn time') plt.title('3D Burntime') plt.axis('scaled') plt.subplot(2, 2, 3) p3 = plt.contour(soln2.position_x.reshape(len(x), len(y)), soln2.position_y.reshape(len(x), len(y)), soln2.burntime.reshape(len(x), len(y))) plt.xlabel('x') plt.ylabel('y') plt.clabel(p3, inline=1, fmt='%1.1f') plt.title('2D Burntime') plt.axis('scaled') plt.subplot(2, 2, 4) p4 = plt.contour(soln3.position_x[::len(z)].reshape(len(x), len(y)), soln3.position_y[::len(z)].reshape(len(x), len(y)), soln3.burntime[::len(z)].reshape(len(x), len(y))) plt.xlabel('x') plt.ylabel('y') plt.clabel(p4, inline=1, fmt='%1.1f') plt.title('3D Burntime, z=0 plane') plt.axis('scaled') plt.tight_layout() plt.show()
# xn = 50 yn = 50 x0 = np.linspace(0.0, a, xn) y0 = np.linspace(0.0, b, yn) x, y = np.meshgrid(x0, y0) xylist = (x, y) # t = 0 # dummy variable plt.title(r'Nonhomogenous solution $\bar T(x,y)$') solver = Rectangle(NonHomogeneousOnly=True, Nsum=100) soln = solver(xylist, t) contourV = np.linspace(0.05, 1.0, 10) pt1 = plt.contour(soln.position_x, soln.position_y, soln.temperature, contourV) manual_locations = [(1, 0.5), (1, 1.0), (1, 1.5), (1, 2.0)] plt.clabel(pt1, inline=1, fontsize=10, manual=manual_locations) # plt.ylim(0, a) plt.xlim(0, b) plt.grid(True) plt.savefig('rectangle_static.pdf') plt.show() # plot the evolution in 2x2 plots at t1,t2,t3,t4 # xn = 30 yn = 30 plt.subplot(2, 2, 1) x0 = np.linspace(0.0, a, xn) y0 = np.linspace(0.0, b, yn) x, y = np.meshgrid(x0, y0)
def decision_boundary_plot(svm, features, vectors, labels, kernel, fileName = None, **args) : title = None if 'title' in args : title = args['title'] xlabel = None if 'xlabel' in args : xlabel = args['xlabel'] ylabel = None if 'ylabel' in args : ylabel = args['ylabel'] fontsize = 'medium' if 'fontsize' in args : fontsize = args['fontsize'] contourFontsize = 10 if 'contourFontsize' in args : contourFontsize = args['contourFontsize'] showColorbar = True if 'showColorbar' in args : showColorbar = args['showColorbar'] show = True if fileName is not None : show = False if 'show' in args : show = args['show'] # setting up the grid delta = 0.005 x = arange(xmin, xmax, delta) y = arange(ymin, ymax, delta) Z = numpy.zeros((len(x), len(y)), numpy.float_) gridX = numpy.zeros((len(x) *len(y), 2), numpy.float_) n = 0 for i in range(len(x)) : for j in range(len(y)) : gridX[n][0] = x[i] gridX[n][1] = y[j] n += 1 if kernel.get_name() == 'Linear' and 'customwandb' in args: kernel.init_optimization_svm(svm) b=svm.get_bias() w=kernel.get_w() kernel.set_w(args['customwandb'][0]) svm.set_bias(args['customwandb'][1]) if kernel.get_name() == 'Linear' and 'drawarrow' in args: kernel.init_optimization_svm(svm) b=svm.get_bias() w=kernel.get_w() s=1.0/numpy.dot(w,w)/1.17 pylab.arrow(0,-b/w[1], w[0]*s,s*w[1], width=0.01, fc='#dddddd', ec='k') grid_features = RealFeatures(numpy.transpose(gridX)) results = svm_test(svm, kernel, features, grid_features) n = 0 for i in range(len(x)) : for j in range(len(y)) : Z[i][j] = results[n] n += 1 cdict = {'red' :((0.0, 0.6, 0.6),(0.5, 0.8, 0.8),(1.0, 1.0, 1.0)), 'green':((0.0, 0.6, 0.6),(0.5, 0.8, 0.8),(1.0, 1.0, 1.0)), 'blue' :((0.0, 0.6, 0.6),(0.5, 0.8, 0.8),(1.0, 1.0, 1.0)), } my_cmap = matplotlib.colors.LinearSegmentedColormap('lightgray',cdict,256) im = pylab.imshow(numpy.transpose(Z), interpolation='bilinear', origin='lower', cmap=my_cmap, extent=(xmin,xmax,ymin,ymax) ) if 'decisionboundaryonly' in args: C1 = pylab.contour(numpy.transpose(Z), [0], origin='lower', linewidths=(3), colors = ['k'], extent=(xmin,xmax,ymin,ymax)) else: C1 = pylab.contour(numpy.transpose(Z), [-1,0,1], origin='lower', linewidths=(1,3,1), colors = ['k','k'], extent=(xmin,xmax,ymin,ymax)) pylab.clabel(C1, inline=1, fmt='%1.1f', fontsize=contourFontsize) # plot the data lab=labels.get_labels() vec=numpy.array(vectors) idx=numpy.where(lab==-1)[0] pylab.scatter(vec[idx,0], vec[idx,1], s=300, c='#4444ff', marker='o', alpha=0.8, zorder=100) idx=numpy.where(lab==+1)[0] pylab.scatter(vec[idx,0], vec[idx,1], s=500, c='#ff4444', marker='s', alpha=0.8, zorder=100) # plot SVs if not 'decisionboundaryonly' in args: training_outputs = svm_test(svm, kernel, features, features) sv_idx=numpy.where(abs(training_outputs)<=1.01)[0] pylab.scatter(vec[sv_idx,0], vec[sv_idx,1], s=100, c='k', marker='o', alpha=0.8, zorder=100) if 'showmovedpoint' in args: x=-0.779838709677 y=-0.1375 pylab.scatter([x], [y], s=300, c='#4e4e61', marker='o', alpha=1, zorder=100, edgecolor='#454548') pylab.arrow(x,y-0.1, 0, -0.8/1.5, width=0.01, fc='#dddddd', ec='k') #pylab.show() if title is not None : pylab.title(title, fontsize=fontsize) if ylabel: pylab.ylabel(ylabel,fontsize=fontsize) if xlabel: pylab.xlabel(xlabel,fontsize=fontsize) if showColorbar : pylab.colorbar(im) # colormap: pylab.hot() if fileName is not None : pylab.savefig(fileName) if show : pylab.show()
def coreContour(self, X, Y, Z, typC, valeur, col): """ calcul des contour sa partir de valeur : valeur[0] : min [1] : max, [2] nb contours, [3] decimales, [4] : 'lin' log' ou 'fix', si [4]:fix, alors [5] est la serie des valeurs de contours""" self.cnv.collections = [] self.cnv.artists = [] V = 11 Zmin = amin(amin(Z)) Zmax = amax(amax(Z * (Z < 1e5))) if Zmax == Zmin: # test min=max -> pas de contour # obj = GraphicObject('contour', Zmin, False, None) # obj.setData([X,Y,Z]);self.addGraphicObject(obj) self.parent.OnMessage(str(typC) + ": valeurs toutes egales a " + str(Zmin)) return if valeur == None: valeur = [Zmin, Zmax, (Zmax - Zmin) / 10.0, 2, "auto", []] # adapter le nombre et la valeur des contours val2 = [float(a) for a in valeur[:3]] if valeur[4] == "log": # cas echelle log n = int((log10(val2[1]) - log10(max(val2[0], 1e-4))) / val2[2]) + 1 V = logspace(log10(max(val2[0], 1e-4)), log10(val2[1]), n) elif (valeur[4] == "fix") and (valeur[5] != None): # fixes par l'utilisateur V = valeur[5] * 1 V.append(V[-1] * 2.0) n = len(V) elif valeur[4] == "lin": # cas echelle lineaire n = int((val2[1] - val2[0]) / val2[2]) + 1 V = linspace(val2[0], val2[1], n) else: # cas automatique n = 11 V = linspace(Zmin, Zmax, n) # ONE DIMENSIONAL r, c = shape(X) if r == 1: X = concatenate([X, X]) Y = concatenate([Y - Y * 0.45, Y + Y * 0.45]) Z = concatenate([Z, Z]) Z2 = ma.masked_where(Z.copy() > 1e5, Z.copy()) # print valeur,n,V # definir les couleurs des contours if col == None: # or (col==[(0,0,0),(0,0,0),(0,0,0),10]): cf = pl.contourf(pl.array(X), pl.array(Y), Z2, V) c = pl.contour(pl.array(X), pl.array(Y), Z2, V) col = [(0, 0, 255), (0, 255, 0), (255, 0, 0), 10] else: r, g, b = [], [], [] lim = ( (0.0, 1.0, 0.0, 0.0), (0.1, 1.0, 0.0, 0.0), (0.25, 0.8, 0.0, 0.0), (0.35, 0.0, 0.8, 0.0), (0.45, 0.0, 1.0, 0.0), (0.55, 0.0, 1.0, 0.0), (0.65, 0.0, 0.8, 0.0), (0.75, 0.0, 0.0, 0.8), (0.9, 0.0, 0.0, 1.0), (1.0, 0.0, 0.0, 1.0), ) for i in range(len(lim)): c1 = lim[i][1] * col[0][0] / 255.0 + lim[i][2] * col[1][0] / 255.0 + lim[i][3] * col[2][0] / 255.0 r.append((lim[i][0], c1, c1)) c2 = lim[i][1] * col[0][1] / 255.0 + lim[i][2] * col[1][1] / 255.0 + lim[i][3] * col[2][1] / 255.0 g.append((lim[i][0], c2, c2)) c3 = lim[i][1] * col[0][2] / 255.0 + lim[i][2] * col[1][2] / 255.0 + lim[i][3] * col[2][2] / 255.0 b.append((lim[i][0], c3, c3)) cdict = {"red": r, "green": g, "blue": b} my_cmap = mpl.colors.LinearSegmentedColormap("my_colormap", cdict, 256) cf = pl.contourf(pl.array(X), pl.array(Y), Z2, V, cmap=my_cmap) c = pl.contour(pl.array(X), pl.array(Y), Z2, V, cmap=my_cmap) for cl in cf.collections: cl.set_alpha(int(col[3]) / 100.0) # print cl obj = GraphicObject("contour", [c, cf], False, None) obj.setData([X, Y, Z]) # obj.setVisible(True) self.addGraphicObject(obj) if valeur == None: fmt = "%1.3f" else: fmt = "%1." + str(valeur[3]) + "f" cl = pl.clabel(c, color="black", fontsize=9, fmt=fmt) obj = GraphicObject("contLabel", cl, False, None) self.addGraphicObject(obj) self.redraw()
def decisionSurface(classifier, fileName = None, **args) : global data global numpy_container classifier.train(data) numContours = 3 if 'numContours' in args : numContours = args['numContours'] title = None if 'title' in args : title = args['title'] markersize=5 fontsize = 'medium' if 'markersize' in args : markersize = args['markersize'] if 'fontsize' in args : fontsize = args['fontsize'] contourFontsize = 10 if 'contourFontsize' in args : contourFontsize = args['contourFontsize'] showColorbar = False if 'showColorbar' in args : showColorbar = args['showColorbar'] show = True if fileName is not None : show = False if 'show' in args : show = args['show'] # setting up the grid delta = 0.01 if 'delta' in args : delta = args['delta'] x = arange(xmin, xmax, delta) y = arange(ymin, ymax, delta) Z = numpy.zeros((len(x), len(y)), numpy.float) gridX = numpy.zeros((len(x) *len(y), 2), numpy.float) n = 0 for i in range(len(x)) : for j in range(len(y)) : gridX[n][0] = x[i] gridX[n][1] = y[j] n += 1 if not numpy_container : gridData = VectorDataSet(gridX) gridData.attachKernel(data.kernel) else : gridData = PyVectorDataSet(gridX) results = classifier.test(gridData) n = 0 for i in range(len(x)) : for j in range(len(y)) : Z[i][j] = results.decisionFunc[n] n += 1 #pylab.figure() im = pylab.imshow(numpy.transpose(Z), interpolation='bilinear', origin='lower', cmap=pylab.cm.gray, extent=(xmin,xmax,ymin,ymax) ) if numContours == 1 : C = pylab.contour(numpy.transpose(Z), [0], origin='lower', linewidths=(3), colors = 'black', extent=(xmin,xmax,ymin,ymax)) elif numContours == 3 : C = pylab.contour(numpy.transpose(Z), [-1,0,1], origin='lower', linewidths=(1,3,1), colors = 'black', extent=(xmin,xmax,ymin,ymax)) else : C = pylab.contour(numpy.transpose(Z), numContours, origin='lower', linewidths=2, extent=(xmin,xmax,ymin,ymax)) pylab.clabel(C, inline=1, fmt='%1.1f', fontsize=contourFontsize) # plot the data scatter(data, markersize=markersize) xticklabels = pylab.getp(pylab.gca(), 'xticklabels') yticklabels = pylab.getp(pylab.gca(), 'yticklabels') pylab.setp(xticklabels, fontsize=fontsize) pylab.setp(yticklabels, fontsize=fontsize) if title is not None : pylab.title(title, fontsize=fontsize) if showColorbar : pylab.colorbar(im) # colormap: pylab.hot() if fileName is not None : pylab.savefig(fileName) if show : pylab.show()
def tsplot_plot(cfg, plot_params): """Plot a TS diagram. Parameters ---------- model_filenames: OrderedDict OrderedDict with model names as keys and input files as values. max_level: float maximum depth level the TS plot shoud go. region: str name of the region predefined in `hofm_regions` function. diagworkdir: str path to work directory. diagplotdir: str path to plotting directory. ncols: str number of columns in the resulting plot (raws will be calculated from total number of plots) cmap: matplotlib.cmap object color map observations: str name of the dataset with observations Returns ------- None """ # Setup a figure nplots = len(plot_params['model_filenames']) ncols = float(plot_params['ncols']) nrows = math.ceil(nplots / ncols) ncols = int(ncols) nrows = int(nrows) nplot = 1 plt.figure(figsize=(8 * ncols, 2 * nrows * ncols)) # loop over models for mmodel in plot_params['model_filenames']: logger.info("Plot tsplot data for %s, region %s", mmodel, plot_params['region']) # load mean data created by `tsplot_data` ifilename_t = genfilename(cfg['work_dir'], 'thetao', mmodel, plot_params['region'], 'tsplot', '.npy') ifilename_s = genfilename(cfg['work_dir'], 'so', mmodel, plot_params['region'], 'tsplot', '.npy') ifilename_depth = genfilename(cfg['work_dir'], 'depth', mmodel, plot_params['region'], 'tsplot', '.npy') temp = np.load(ifilename_t, allow_pickle=True) salt = np.load(ifilename_s, allow_pickle=True) depth = np.load(ifilename_depth, allow_pickle=True) # Still old fashioned way to setup a plot, works best for now. plt.subplot(nrows, ncols, nplot) # calculate background with density isolines si2, ti2, dens = dens_back(33, 36., -2, 6) # convert form Kelvin if needed if temp.min() > 100: temp = temp - 273.15 # plot the background contour_plot = plt.contour(si2, ti2, dens, colors='k', levels=np.linspace(dens.min(), dens.max(), 15), alpha=0.3) # plot the scatter plot plt.scatter(salt[::], temp[::], c=depth, s=3.0, cmap=plot_params['cmap'], edgecolors='none', vmax=cfg['tsdiag_depth']) # adjust the plot plt.clabel(contour_plot, fontsize=12, inline=1, fmt='%1.1f') plt.xlim(33, 36.) plt.ylim(-2.1, 6) plt.xlabel('Salinity', size=20) plt.ylabel(r'Temperature, $^{\circ}$C', size=20) plt.xticks(size=15) plt.yticks(size=15) # setup the colorbar colorbar = plt.colorbar(pad=0.03) colorbar.ax.get_yaxis().labelpad = 15 colorbar.set_label('depth, m', rotation=270, size=20) colorbar.ax.tick_params(labelsize=15) plt.title(mmodel, size=20) nplot = nplot + 1 plt.tight_layout() # save the plot pltoutname = genfilename(cfg['plot_dir'], 'tsplot', region=plot_params['region'], data_type='tsplot') plt.savefig(pltoutname, dpi=100) plot_params['basedir'] = cfg['plot_dir'] plot_params['ori_file'] = [ifilename_t] plot_params['areacello'] = None plot_params['mmodel'] = None provenance_record = get_provenance_record(plot_params, 'tsplot', 'png') with ProvenanceLogger(cfg) as provenance_logger: provenance_logger.log(pltoutname + '.png', provenance_record)
for k in range(len(SFR)): vol[:,k] = SFR[k]*vol[:,k]*eta[k] Z = vol Z = Z[0:5] Y = Y[0:5] #can try this interpolate thing later, for now it seems as though vol declines too quickly for it to want to do that #f_z = interpolate.interp2d(X, Y, vol, kind ='cubic') #xnew = np.linspace(1, 10, 0.5) #ynew = np.linspace(1, 60, 1) #znew = f_z(xnew, ynew) plt.clf() #plt.contour(xnew, ynew, znew) plt.clabel(CS, inline=1, fontsize=10) CS = plt.contour(X, Y, Z) plt.xlabel("redshift") plt.ylabel("$\mu$") plt.title('N(z, $\mu$), for flat $\eta(z)$ and SFR') plt.savefig("number_SN_lin.png") plt.clf() plt.plot(z_list, SFR) plt.xlabel("redshift") plt.ylabel("SFR") plt.savefig("SFR_flat.png") plt.show()
fig = plt.figure() #2行2列的子图中的第一个,第一行的第一列 subfig1 = fig.add_subplot(2, 2, 1) #画等值线云图 surf1 = plt.contourf(X, Y, moni_block(moni_dict)) #添加色标 fig.colorbar(surf1) #添加标题 plt.title('contourf+colorbar') #d第二个子图,第一行的第二列 subfig2 = fig.add_subplot(2, 2, 2) #画等值线 surf2 = plt.contour(X, Y, moni_block(moni_dict)) #等值线上添加标记 plt.clabel(surf2, inline=1, fontsize=10, cmap='jet') #添加标题 plt.title('contour+clabel') #第三个子图,第二行的第一列 subfig3 = fig.add_subplot(2, 2, 3, projection='3d') #画三维边框 surf3 = subfig3.plot_wireframe(X, Y, moni_block(moni_dict), rstride=10, cstride=10, color='y') #画等值线 plt.contour(X, Y, f(X, Y)) #设置标题
rn = 50 thetan = 50 r0 = np.linspace(a, b, rn) theta0 = np.linspace(0, np.pi / 2, thetan) r, theta = np.meshgrid(r0, theta0) rtheta_list = (r, theta) solver = CylindricalSandwich() # NonHomogeneousOnly = True soln = solver(rtheta_list, t) # contour plots contourV = np.linspace(0.001, 1.5, 200) pt1 = plt.contour(soln.angle_theta, soln.position_r, soln.temperature, contourV) manual_locations = [(0.25, 0.55), (0.5, 0.55), (1.0, 0.55), (1.4, 0.55)] plt.clabel(pt1, inline=1, fontsize=10, manual=manual_locations) plt.title(r'Nonhomogenous solution $T(x,y,t)$ at $t=0.01$') plt.ylim(a, b) plt.xlim(0, np.pi / 2) plt.ylabel(r'$T$', fontsize=20) plt.xlabel(r'$\theta$', fontsize=20) plt.grid(True) plt.savefig('cylindrical_sandwich.pdf') plt.show() # line outs pt1 = plt.plot(soln.angle_theta[:, 2], soln.temperature[:, 2]) pt2 = plt.plot(soln.angle_theta[:, 10], soln.temperature[:, 10]) # plt.title(r'Nonhomogenous solution $T(x,y,t)$ at $t=0.01$')