def __call__(self,iteration): p = self.t.calcPress(iteration,pOnly=True) plt.imshow(p[:,0,:],origin=0) plt.axis('tight') plt.colorbar()
def plotmaptime(): pcolormesh(yoko, time*1e6, absolute(Magcom)) title("Reflection vs flux \n and time (1 us pulse) at 4.46 GHz") xlabel("Flux (V)") ylabel("Time (us)") #ylim(0, 1.5) colorbar()
def plots(i,tcodnt, temp, forecast,added_tcodnt,n_steps,path, rsdlsc,rsdlpctgc, sqrpctgc,a,b,c,d,e): fig=mp.figure(figsize=[15,6])#5:2,89mm grid=mp.GridSpec(3,36,wspace=1,hspace=0.4) ax=mp.subplot(grid[:2,:18]) cpplot(i,tcodnt, temp, forecast,added_tcodnt,n_steps,path) #rscplot(i,tcodnt, rsdlsc, rsdlpctgc, sqrpctgc,path) ax=mp.subplot(grid[2,:18]) im1=colorbar(ax,tcodnt, rsdlsc,i,0,-1,c**2) ax.set_yticks([]) ax=mp.subplot(grid[2,21:35]) im2=colorbar(ax,tcodnt, rsdlsc,i,a,b,int(c/2)) ax.set_yticks([]) ax=mp.subplot(grid[:2,21:35]) partial_plot_for_ahead_interval(i,tcodnt, temp, forecast,added_tcodnt,n_steps,path,rsdlpctgc,a,b) ax1=mp.subplot(grid[:,35]) clb1=mp.colorbar(im2,cax=ax1,extend='both') #clb1.set_label('residuals',fontsize=12,color='grey') ax2=mp.subplot(grid[:,18]) clb2=mp.colorbar(im1,cax=ax2,extend='both') clb1.set_label('residuals',fontsize=size) # ax=mp.subplot(grid[:2,32:35]) # partial_plot_for_ahead_interval(i,tcodnt, temp, forecast,added_tcodnt,n_steps,path,rsdlpctgc,d,e) # ax=mp.subplot(grid[2,32:35]) # im3=colorbar(ax,tcodnt, rsdlsc,i,d,e,int(c/5)) # ax.set_yticks([]) # ax3=mp.subplot(grid[:,35]) # clb3=mp.colorbar(im3,cax=ax3,extend='both') # clb3.set_label('residuals',fontsize=size,color='grey') mp.savefig((str(path)+'\\'+'results'+'\\'+'Accuracy_Graph_%d'+'.jpg')%i,format='jpg',dpi=2000)
def main(): gw = gridworld() a = agent(gw) for epoch in range(20): a.initEpoch() while True: rwd, stat, act = a.takeAction() a.updateQ(rwd, stat, act) if gw.status() == 'Goal': break if mod(a.counter, 10)==0: print(gw.state()) print(gw.field()) print('Finished') print(a.counter) print(gw.state()) print(gw.field()) Q = transpose(a.Q(), (2,0,1)) for i in range(4): plt.subplot(2,2,i) plt.imshow(Q[i], interpolation='nearest') plt.title(a.actions()[i]) plt.colorbar() plt.show()
def plotmapdBtime(): pcolormesh(yoko, time*1e6, dB(S11c), vmin=-65, vmax=-30) title("Reflection (dB) vs flux \n and time (1 us pulse) at 4.46 GHz") xlabel("Flux (V)") ylabel("Time (us)") #ylim(0, 1.5) colorbar()
def test_minimized_rasterized(): # This ensures that the rasterized content in the colorbars is # only as thick as the colorbar, and doesn't extend to other parts # of the image. See #5814. While the original bug exists only # in Postscript, the best way to detect it is to generate SVG # and then parse the output to make sure the two colorbar images # are the same size. from xml.etree import ElementTree np.random.seed(0) data = np.random.rand(10, 10) fig, ax = plt.subplots(1, 2) p1 = ax[0].pcolormesh(data) p2 = ax[1].pcolormesh(data) plt.colorbar(p1, ax=ax[0]) plt.colorbar(p2, ax=ax[1]) buff = io.BytesIO() plt.savefig(buff, format='svg') buff = io.BytesIO(buff.getvalue()) tree = ElementTree.parse(buff) width = None for image in tree.iter('image'): if width is None: width = image['width'] else: if image['width'] != width: assert False
def atest_interpolation_coast(self): """Test interpolation.""" reader = reader_ROMS_native.Reader('/disk2/data/SVIM/ocean_avg_20081201.nc') num_points = 50 np.random.seed(0) # To get the same random numbers each time lons = np.random.uniform(12, 16, num_points) lats = np.random.uniform(68.3, 68.3, num_points) z = np.random.uniform(-100, 0, num_points) x, y = reader.lonlat2xy(lons, lats) variables = ['x_sea_water_velocity', 'y_sea_water_velocity', 'sea_water_temperature'] # Read a block of data covering the points data = reader.get_variables(variables, time=reader.start_time, x=x, y=y, z=z, block=True) import matplotlib.pyplot as plt plt.imshow(data['x_sea_water_velocity'][0,:,:]) plt.colorbar() plt.show() b = ReaderBlock(data, interpolation_horizontal='nearest') env, prof = b.interpolate(x, y, z, variables, profiles=['x_sea_water_velocity'], profiles_depth=[-30, 0])
def implot(plt, x, y, Z, ax=None, colorbar=True, **kwargs): """Image plot of general data (like imshow but with non-pixel axes). Parameters ---------- plt : plot object Plot object, typically `matplotlib.pyplot`. x : (M,) array_like Vector of x-axis points, must be linear (equally spaced). y : (N,) array_like Vector of y-axis points, must be linear (equally spaced). Z : (M, N) array_like Matrix of data to be displayed, the value at each (x, y) point. ax : axis object (optional) A specific axis to plot on (defaults to `plt.gca()`). colorbar: boolean (optional) Whether to plot a colorbar. **kwargs Additional arguments for `ax.imshow`. """ ax = plt.gca() if ax is None else ax def is_linear(x): diff = np.diff(x) return np.allclose(diff, diff[0]) assert is_linear(x) and is_linear(y) image = ax.imshow(Z, aspect='auto', extent=(x[0], x[-1], y[-1], y[0]), **kwargs) if colorbar: plt.colorbar(image, ax=ax)
def _plot_loading(loadings, idx, axes_manager, ax=None, comp_label='PC', no_nans=True, calibrate=True, cmap=plt.cm.gray): if ax is None: ax = plt.gca() if no_nans: loadings = np.nan_to_num(loadings) if axes_manager.navigation_dimension == 2: extent = None # get calibration from a passed axes_manager shape = axes_manager._navigation_shape_in_array if calibrate: extent = (axes_manager._axes[0].low_value, axes_manager._axes[0].high_value, axes_manager._axes[1].high_value, axes_manager._axes[1].low_value) im = ax.imshow(loadings[idx].reshape(shape), cmap=cmap, extent=extent, interpolation='nearest') div = make_axes_locatable(ax) cax = div.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax) elif axes_manager.navigation_dimension == 1: if calibrate: x = axes_manager._axes[0].axis else: x = np.arange(axes_manager._axes[0].size) ax.step(x, loadings[idx]) else: messages.warning_exit('View not supported')
def plot_jacobian(A, name, cmap= plt.cm.coolwarm, normalize=True, precision=1e-6): """ Customized visualization of jacobian matrices for observing sparsity patterns """ plt.figure() fig, ax = plt.subplots() if normalize is True: plt.imshow(A, interpolation='none', cmap=cmap, norm = mpl.colors.Normalize(vmin=-1.,vmax=1.)) else: plt.imshow(A, interpolation='none', cmap=cmap) plt.colorbar(format=ticker.FuncFormatter(fmt)) ax.spy(A, marker='.', markersize=0, precision=precision) ax.spines['right'].set_visible(True) ax.spines['bottom'].set_visible(True) ax.xaxis.set_ticks_position('top') ax.yaxis.set_ticks_position('left') xlabels = np.linspace(0, A.shape[0], 5, True, dtype=int) ylabels = np.linspace(0, A.shape[1], 5, True, dtype=int) plt.xticks(xlabels) plt.yticks(ylabels) plt.savefig(name, bbox_inches='tight', pad_inches=0.05) plt.close() return
def pltytfield(): fig=plt.figure() ppy=yt.ProjectionPlot(ds, "x", "Bxy", weight_field="density") #Project X-component of B-field from z-direction By=ppy._frb["Bxy"] ax=fig.add_subplot(111) plt.xticks(tick_locs,tick_lbls) plt.yticks(tick_locs,tick_lbls) Bymag=ax.pcolormesh(np.log10(By)) cbar_m=plt.colorbar(Bymag) cbar_m.set_label("Bxy") plt.title("Bxy in yz plane") fig=plt.figure() ppy=yt.ProjectionPlot(ds, "y", "Bxy", weight_field="density") #Project X-component of B-field from z-direction By=ppy._frb["Bxy"] ax=fig.add_subplot(111) plt.xticks(tick_locs,tick_lbls) plt.yticks(tick_locs,tick_lbls) Bymag=ax.pcolormesh(np.log10(By)) cbar_m=plt.colorbar(Bymag) cbar_m.set_label("Bxy") plt.title("Bxy in xz plane") fig=plt.figure() ppy=yt.ProjectionPlot(ds, "z", "Bxy", weight_field="density") #Project X-component of B-field from z-direction By=ppy._frb["Bxy"] ax=fig.add_subplot(111) plt.xticks(tick_locs,tick_lbls) plt.yticks(tick_locs,tick_lbls) Bymag=ax.pcolormesh(np.log10(By)) cbar_m=plt.colorbar(Bymag) cbar_m.set_label("Bxy") plt.title("Bxy in xy plane")
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label')
def run(meth = 'moment'): out,srts = bs.run0(arr = arr, itr = 2, meth = meth) f = myplots.fignum(3,(12,6)) ax = f.add_subplot(111) csrts = [s for s in srts if len(s) == len(cols)][0] rsrts = [s for s in srts if len(s) == len(rows)][0] cprint = [rows[rs] for rs in rsrts] rprint = [cols[cs] for cs in csrts] im = ax.imshow(out, interpolation= 'nearest', cmap = plt.get_cmap('OrRd'), ) #flip the rows and columns... looks better. ax.set_xticks(arange(len(cols))+.25) ax.set_yticks(arange(len(rows))+.25) ax.set_yticklabels([e for e in cprint]) ax.set_xticklabels(rprint) print 'rows: \n{0}'.format(', '.join([e.strip() for e in rprint])) print print 'cols: \n{0}'.format(', '.join([e.strip() for e in cprint])) plt.colorbar(im) f.savefig(myplots.figpath('correlation_plot_2_4_{0}.pdf') .format(meth)) return
def streamlineBxz_dens(): fig=plt.figure() ppy=yt.ProjectionPlot(ds, "y", "Bxz", weight_field="density") #Project X-component of B-field from z-direction By=ppy._frb["density"] ax=fig.add_subplot(111) plt.xticks(tick_locs,tick_lbls) plt.yticks(tick_locs,tick_lbls) Bymag=ax.pcolormesh(np.log10(By), cmap="YlGn") cbar_m=plt.colorbar(Bymag) cbar_m.set_label("density") res=800 #densxy=Density2D(0,1) #integrated density along given axis U=Flattenx(0,1) #X-magnetic field integrated along given axis V=Flattenz(0,1) #Z-magnetic field #U=np.asarray(zip(*x2)[::-1]) #rotate the matrix 90 degrees to correct orientation to match projected plots #V=np.asarray(zip(*y2)[::-1]) norm=np.sqrt(U**2+V**2) #magnitude of the vector Unorm=U/norm #normalise vectors Vnorm=V/norm #mask_Unorm=np.ma.masked_where(densxy<np.mean(densxy),Unorm) #create a masked array of Unorm values only in high density regions #mask_Vnorm=np.ma.masked_where(densxy<np.mean(densxy),Vnorm) X,Y=np.meshgrid(np.linspace(0,res,64, endpoint=True),np.linspace(0,res,64,endpoint=True)) streams=plt.streamplot(X,Y,Unorm,Vnorm,color=norm*1e6,density=(3,3),cmap=plt.cm.autumn) cbar=plt.colorbar(orientation="horizontal") cbar.set_label('Bxz streamlines (uG)') plt.title("Bxz streamlines on weighted density projection") plt.xlabel("(1e4 AU)") plt.ylabel("(1e4 AU)")
def TuningResponseArea(tuningCurves, unitKey='', figPath=[]): """ Plot the tuning response area for tuning curve data. :param tuningCurves: pandas.DataFrame from spreadsheet with experimental data loaded from Excel file :type tuningCurves: pandas.core.DataFrame :param unitKey: identifying string for data, possibly unit name/number and test number :type unitKey: str :param figPath: Directory location for plots to be saved :type figPath: str """ f = plt.figure() colorRange = (-10,10.1) I = np.unique(np.array(tuningCurves['intensity'])) F = np.array(tuningCurves['freq']) R = np.array(np.zeros((len(I), len(F)))) for ci, i in enumerate(I): for cf, f in enumerate(F): R[ci,cf] = tuningCurves['response'].where(tuningCurves['intensity']==i).where(tuningCurves['freq']==f).dropna().values[0] levelRange = np.arange(colorRange[0], colorRange[1], (colorRange[1]-colorRange[0])/float(25*(colorRange[1]-colorRange[0]))) sns.set_context(rc={"figure.figsize": (7, 4)}) ax = plt.contourf(F, I, R)#, vmin=colorRange[0], vmax=colorRange[1], levels=levelRange, cmap = cm.bwr ) plt.colorbar() # plt.title(unit, fontsize=14) plt.xlabel('Frequency (kHz)', fontsize=14) plt.ylabel('Intensity (dB)', fontsize=14) if len(figPath)>0: plt.savefig(figPath + 'tuningArea_' + unitKey +'.png')
def plot_heat_net(net_mat, sectors): """Plot a heat map of the net relations. Parameters ---------- net_mat: np.ndarray the net represented in a matrix way. sectors: list the name of the elements of the adjacency matrix network. Returns ------- fig: matplotlib.pyplot.figure the figure of the matrix heatmap. """ vmax = np.sort([np.abs(net_mat.max()), np.abs(net_mat.min())])[::-1][0] n_sectors = len(sectors) assert(net_mat.shape[0] == net_mat.shape[1]) assert(n_sectors == len(net_mat)) fig = plt.figure() plt.imshow(net_mat, interpolation='none', cmap=plt.cm.RdYlGn, vmin=-vmax, vmax=vmax) plt.xticks(range(n_sectors), sectors) plt.yticks(range(n_sectors), sectors) plt.xticks(rotation=90) plt.colorbar() return fig
def _imshow_tfr(ax, ch_idx, tmin, tmax, vmin, vmax, onselect, ylim=None, tfr=None, freq=None, vline=None, x_label=None, y_label=None, colorbar=False, picker=True, cmap='RdBu_r', title=None): """ Aux function to show time-freq map on topo """ import matplotlib.pyplot as plt from matplotlib.widgets import RectangleSelector extent = (tmin, tmax, freq[0], freq[-1]) img = ax.imshow(tfr[ch_idx], extent=extent, aspect="auto", origin="lower", vmin=vmin, vmax=vmax, picker=picker, cmap=cmap) if isinstance(ax, plt.Axes): if x_label is not None: ax.set_xlabel(x_label) if y_label is not None: ax.set_ylabel(y_label) else: if x_label is not None: plt.xlabel(x_label) if y_label is not None: plt.ylabel(y_label) if colorbar: plt.colorbar(mappable=img) if title: plt.title(title) if not isinstance(ax, plt.Axes): ax = plt.gca() ax.RS = RectangleSelector(ax, onselect=onselect) # reference must be kept
def _erfimage_imshow(ax, ch_idx, tmin, tmax, vmin, vmax, ylim=None, data=None, epochs=None, sigma=None, order=None, scalings=None, vline=None, x_label=None, y_label=None, colorbar=False, cmap='RdBu_r'): """Aux function to plot erfimage on sensor topography""" from scipy import ndimage import matplotlib.pyplot as plt this_data = data[:, ch_idx, :].copy() ch_type = channel_type(epochs.info, ch_idx) if ch_type not in scalings: raise KeyError('%s channel type not in scalings' % ch_type) this_data *= scalings[ch_type] if callable(order): order = order(epochs.times, this_data) if order is not None: this_data = this_data[order] if sigma > 0.: this_data = ndimage.gaussian_filter1d(this_data, sigma=sigma, axis=0) ax.imshow(this_data, extent=[tmin, tmax, 0, len(data)], aspect='auto', origin='lower', vmin=vmin, vmax=vmax, picker=True, cmap=cmap, interpolation='nearest') if x_label is not None: plt.xlabel(x_label) if y_label is not None: plt.ylabel(y_label) if colorbar: plt.colorbar()
def imshow_active_cells(grid, values, var_name=None, var_units=None, grid_units=(None, None), symmetric_cbar=False, cmap='pink'): """ .. deprecated:: 0.6 Use :meth:`imshow_active_cell_grid`, above, instead. """ data = values.view() data.shape = (grid.shape[0]-2, grid.shape[1]-2) y = np.arange(data.shape[0]) - grid.dx * .5 x = np.arange(data.shape[1]) - grid.dx * .5 if symmetric_cbar: (var_min, var_max) = (data.min(), data.max()) limit = max(abs(var_min), abs(var_max)) limits = (-limit, limit) else: limits = (None, None) plt.pcolormesh(x, y, data, vmin=limits[0], vmax=limits[1], cmap=cmap) plt.gca().set_aspect(1.) plt.autoscale(tight=True) plt.colorbar() plt.xlabel('X (%s)' % grid_units[1]) plt.ylabel('Y (%s)' % grid_units[0]) if var_name is not None: plt.title('%s (%s)' % (var_name, var_units)) plt.show()
def demo_locatable_axes_hard(fig1): from mpl_toolkits.axes_grid1 import SubplotDivider, LocatableAxes, Size divider = SubplotDivider(fig1, 2, 2, 2, aspect=True) # axes for image ax = LocatableAxes(fig1, divider.get_position()) # axes for colorbar ax_cb = LocatableAxes(fig1, divider.get_position()) h = [Size.AxesX(ax), Size.Fixed(0.05), Size.Fixed(0.2)] # main axes # padding, 0.1 inch # colorbar, 0.3 inch v = [Size.AxesY(ax)] divider.set_horizontal(h) divider.set_vertical(v) ax.set_axes_locator(divider.new_locator(nx=0, ny=0)) ax_cb.set_axes_locator(divider.new_locator(nx=2, ny=0)) fig1.add_axes(ax) fig1.add_axes(ax_cb) ax_cb.axis["left"].toggle(all=False) ax_cb.axis["right"].toggle(ticks=True) Z, extent = get_demo_image() im = ax.imshow(Z, extent=extent, interpolation="nearest") plt.colorbar(im, cax=ax_cb) plt.setp(ax_cb.get_yticklabels(), visible=False)
def plot_confusion_matrix(cm, labels, axis=None, fontsize=13, colorbar=False): from matplotlib import pyplot as plt title = 'Confusion matrix' cmap = plt.cm.Blues # column normalize if np.max(cm) > 1: cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] else: cm_normalized = cm if axis is None: axis = plt.gca() im = axis.imshow(cm_normalized, interpolation='nearest', cmap=cmap) axis.set_title(title) # axis.get_figure().colorbar(im) tick_marks = np.arange(len(labels)) axis.set_xticks(tick_marks) axis.set_yticks(tick_marks) axis.set_xticklabels(labels, rotation=90, fontsize=fontsize) axis.set_yticklabels(labels, fontsize=fontsize) axis.set_ylabel('True label') axis.set_xlabel('Predicted label') if colorbar == 'all': fig = axis.get_figure() axes = fig.get_axes() fig.colorbar(im, ax=axes) elif colorbar: plt.colorbar(im, ax=axis) # axis.tight_layout() return axis
def el_plot(data, Map=False, show=True): """ Plot the elevation for the region from the last time series :Parameters: **data** -- the standard python data dictionary **Map** -- {True, False} (optional): Optional argument. If True, the elevation will be plotted on a map. """ trigrid = data['trigrid'] plt.gca().set_aspect('equal') plt.tripcolor(trigrid, data['zeta'][-1,:]) plt.colorbar() plt.title("Elevation") if Map: #we set the corners of where the map should show up llcrnrlon, urcrnrlon = plt.xlim() llcrnrlat, urcrnrlat = plt.ylim() #we construct the map. Note that resolution serves to increase #or decrease the detail in the coastline. Currently set to #'i' for 'intermediate' m = Basemap(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, \ resolution='i', suppress_ticks=False) #set color for continents. Default is grey. m.fillcontinents(color='ForestGreen') m.drawmapboundary() m.drawcoastlines() if show: plt.show()
def corrplot(C, cmap=None, cmap_range=(0.,1.), cbar=True, fontsize=14, **kwargs): """ Plots values in a correlation matrix """ ax = kwargs['ax'] n = len(C) # defaults if cmap is None: if min(cmap_range) >= 0: cmap = "OrRd" elif max(cmap_range) <= 0: cmap = "RdBu" else: cmap = "gray" # remove values rr, cc = np.triu_indices(n, k=1) C[rr, cc] = np.nan vmin, vmax = cmap_range img = ax.imshow(C, cmap=cmap, vmin=vmin, vmax=vmax, aspect='equal') if cbar: plt.colorbar(img) #, shrink=0.75) for j in range(n): for i in range(j+1,n): ax.text(i, j, '{:0.2f}'.format(C[i,j]), fontsize=fontsize, fontdict={'ha': 'center', 'va': 'center'}) noticks(ax=ax)
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=None, zmin=1): """This function prints and plots the confusion matrix for the intent classification. Normalization can be applied by setting `normalize=True`.""" import numpy as np zmax = cm.max() plt.imshow(cm, interpolation='nearest', cmap=cmap if cmap else plt.cm.Blues, aspect='auto', norm=LogNorm(vmin=zmin, vmax=zmax)) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=90) plt.yticks(tick_marks, classes) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] logger.info("Normalized confusion matrix: \n{}".format(cm)) else: logger.info("Confusion matrix, without normalization: \n{}".format(cm)) thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.ylabel('True label') plt.xlabel('Predicted label')
def __call__(self,u,w,bx,by,bz,b2,t): q = 8 map = cm.red_blue() if self.x == None: nx = u.shape[2] nz = u.shape[0] self.x,self.y = np.meshgrid(range(nx),range(nz)) x,y = self.x,self.y avgu = np.average(u,1) avgw = np.average(w,1) avgbx = np.average(bx,1) avgby = np.average(by,1) avgbz = np.average(bz,1) avgb2 = np.average(b2,1) avgt = np.average(t,1) plt.subplot(121) plt.imshow(avgt,cmap=map,origin='lower') plt.colorbar() plt.quiver(x[::q,::q],y[::q,::q],avgu[::q,::q],avgw[::q,::q]) plt.title('Tracer-Vel') plt.axis("tight") plt.subplot(122) plt.imshow(avgby,cmap=map,origin='lower') plt.colorbar() plt.quiver(x[::q,::q],y[::q,::q],avgbx[::q,::q],avgbz[::q,::q]) plt.title('By-Twist') plt.axis("tight")
def get_heatmap(data_mat, name_for_saving_files, pp,stimulus_on_time, stimulus_off_time,delta_ff, f0_start, f0_end): #Plot heatmap for validation A1 = np.reshape(data_mat, (np.size(data_mat,0)*np.size(data_mat,1), np.size(data_mat,2))) if delta_ff == 1: delta_ff_A1 = np.zeros(np.shape(A1)) for ii in xrange(0,np.size(A1,0)): delta_ff_A1[ii,:] = (A1[ii,:]-np.mean(A1[ii,f0_start:f0_end]))/(np.std(A1[ii,f0_start:f0_end])+0.1) B = np.argsort(np.mean(delta_ff_A1, axis=1)) print np.max(delta_ff_A1) else: B = np.argsort(np.mean(A1, axis=1)) print np.max(A1) with sns.axes_style("white"): C = A1[B,:][-2000:,:] fig2 = plt.imshow(C,aspect='auto', cmap='jet', vmin = np.min(C), vmax = np.max(C)) plot_vertical_lines_onset(stimulus_on_time) plot_vertical_lines_offset(stimulus_off_time) plt.title(name_for_saving_files) plt.colorbar() fig2 = plt.gcf() pp.savefig(fig2) plt.close()
def plot_map(AX, fname, mmin=0,mmax=1, annot='A', xoff=False,yoff=False, xlab='None', ylab='None', aspect=False, row_lab=None, col_lab=None, log=False): global xtix, ytix, xtix_loc, ytix_loc, fsa, fs mmap = np.genfromtxt(fname, delimiter=',') if log: mmap = np.log(mmap) im = AX.pcolor(mmap, vmin=mmin, vmax=mmax) plt.colorbar(im, ax=AX) AX.annotate(annot, (0,0), (0.02,0.9), color='white', fontsize= fsa, fontweight='bold', xycoords='data', textcoords='axes fraction') if row_lab != None: AX.annotate(row_lab, xy=(0.0, 0.5), size='x-large', ha='right', va='center', xytext= (-4.5, 5))#(-ax.yaxis.labelpad - pad, 0),xycoords=ax.yaxis.label, textcoords='offset points' if col_lab != None: AX.set_title(col_lab) AX.set_xticks(xtix_loc) AX.set_yticks(ytix_loc) if xoff: AX.set_xticklabels('') else: AX.set_xticklabels(xtix) if yoff: AX.set_yticklabels('') else: AX.set_yticklabels(ytix) if xlab != 'None': AX.set_xlabel(xlab, fontsize = fs) if ylab != 'None': AX.set_ylabel(ylab, fontsize = fs) if aspect: AX.set_aspect('equal', 'datalim')
def lasso_regression(features, solutions, verbose=0): columns = solutions.columns clf = Lasso(alpha=1e-4, max_iter=5000) print('Training Model... ') clf.fit(features, solutions) feature_coeff = clf.coef_ features_importances = np.zeros((169, 3)) for idx in range(3): features_importance = np.reshape(feature_coeff[idx, :], (169, 8)) features_importance = np.max(features_importance, axis=1) features_importances[:, idx] = features_importance features_importance_max = np.max(features_importances, axis=1) features_importance_max = np.reshape(features_importance_max, (13, 13)) plt.pcolor(features_importance_max) plt.title("Feature importance for HoG") plt.colorbar() plt.xticks(arange(0.5,13.5), range(1, 14)) plt.yticks(arange(0.5,13.5), range(1, 14)) plt.axis([0, 13, 0, 13]) plt.show() print('Done Training') return (clf, columns)
def plotTimeseries(mytimes,myyears,times,mydata,myvar,depthlevels,mytype): depthlevels=-np.asarray(depthlevels) ax = figure().add_subplot(111) y,x = np.meshgrid(depthlevels,times) mydata=np.rot90(mydata) if myvar=='temp': levels = np.arange(-2,16,1) if myvar=='salt': levels = np.arange(mydata.min(),mydata.max()+0.1,0.05) if mytype=="T-CLASS3-IC_CHANGE": levels = np.arange(mydata.min(),mydata.max()+0.1,0.1) if mytype=="S-CLASS3-IC_CHANGE": levels = np.arange(mydata.min(),mydata.max()+0.1,0.05) print mydata.min(), mydata.max() cs=contourf(x,y,mydata,levels,cmap=cm.get_cmap('RdBu_r',len(levels)-1)) plt.colorbar(cs) xticks(mytimes,myyears,rotation=-90) plotfile='figures/'+str(mytype)+'_'+str(myvar)+'_alldepths.pdf' plt.savefig(plotfile,dpi=300) print 'Saved figure file %s\n'%(plotfile)
def test_unimodality_of_GEV(self): x0 = 1500 mu = 1000 data = np.array([x0]) ksi = np.arange(-2, 2, 0.01) sigma = np.arange(10, 8000, 10) n_ksi = len(ksi) n_sigma = len(sigma) z = np.zeros((n_ksi, n_sigma)) for i, the_ksi in enumerate(ksi): for j, the_sigma in enumerate(sigma): z[i, j] = gevfit.objective_function_stationary_high([the_sigma, mu, the_ksi], data) sigma, ksi = np.meshgrid(sigma, ksi) z = np.ma.masked_where(z == gevfit.BIG_NUM, z) z = np.ma.masked_where(z > 9, z) plt.figure() plt.pcolormesh(ksi, sigma, z) plt.colorbar() plt.xlabel('$\\xi$') plt.ylabel('$\\sigma$') plt.title('$\\mu = %.1f, x = %.1f$' % (mu, x0)) plt.show() pass
def plot(varName, label, cmap, scale=None): # the file name is the variable followed by the zero-padded time intex imageFileName = '%s/%s_%04i.png' % (outFolder, varName, timeIndex) if (os.path.exists(imageFileName)): # the image exists so we're going to save time and not replot it return # get the variable from the netCDF file try: var = ncFile.variables[varName] except KeyError: return # the axes are 'xy', 'xz', or 'yz' axes = '%s%s' % (var.dimensions[2][1], var.dimensions[1][1]) # get the extent based on the axes extent = extents[axes] # aspect ratio if (axes == 'xy'): # pixels are 1:1 aspectRatio = None else: # stretch the axes to fill the plot area aspectRatio = 'auto' field = ncFile.variables[varName][timeIndex, :, :] missingValue = 9.9692099683868690e36 if (numpy.ma.amax(field) == missingValue): # the array didnt' get masked properly, so do it manually field = numpy.ma.masked_array(field, mask=(field == missingValue), dtype=float) else: # convert from float32 to float64 to avoid overflow/underflow problems if hasattr(field, 'mask'): field = numpy.ma.masked_array(field, mask=field.mask, dtype=float) else: field = numpy.array(field, dtype=float) # scale the variable if a scale is given if scale is not None: field *= scale # get the plotting limits from the dictionary of limits we created (lower, upper) = limits[varName] # make a figure plt.figure(1, figsize=[16, 9], dpi=100, facecolor='w') # activate the specified colorbar and set the background color cmap = plt.get_cmap(cmap) cmap.set_bad(backgroundColor) # clear the figure from the last plot plt.clf() # plot the data as an image plt.imshow(field, extent=extent, cmap=cmap, vmin=lower, vmax=upper, aspect=aspectRatio, interpolation='nearest') plt.colorbar() plt.title(label) if (axes == 'xy'): # y axis will be upside down in imshow, which we don't want for xy plt.gca().invert_yaxis() plt.xlabel('x (km)') plt.ylabel('y (km)') elif (axes == 'xz'): # upside-down y axis is okay plt.xlabel('x (km)') plt.ylabel('z (m)') else: # upside-down y axis is okay plt.xlabel('y (km)') plt.ylabel('z (m)') if (axes in ['xz', 'yz']) and (z[0] < z[-1]): # flip the y axis plt.gca().invert_yaxis() # save the figure as an image plt.tight_layout() plt.draw() plt.savefig(imageFileName, dpi=100) plt.close()
def plot_image(self, band): plt.imshow(band, cmap='RdYlGn') plt.colorbar() plt.show()
import numpy as np import matplotlib.pyplot as mp u = np.linspace(-2.5, 2.5, 501) x, y = np.meshgrid(u, u) z = np.sinc(x * y) mp.gcf().set_facecolor(np.ones(3) * 240 / 255) mp.subplot(121) mp.title('Ordinary Contour', fontsize=16) mp.xlabel('x', fontsize=12) mp.ylabel('y', fontsize=12) mp.tick_params(labelsize=10) mp.grid(linestyle=':') cntr = mp.contour(x, y, z, 5, cmap='jet') mp.clabel(cntr, inline_spacing=1, fmt='%.2f', fontsize=8, cmap='jet') mp.colorbar(cntr).set_label('sinc-2D', fontsize=12) mp.subplot(122) mp.title('Filled Contour', fontsize=16) mp.xlabel('x', fontsize=12) mp.ylabel('y', fontsize=12) mp.tick_params(labelsize=10) mp.grid(linestyle=':') cntrf = mp.contourf(x, y, z, 20, cmap='jet') mp.colorbar(cntrf).set_label('sinc-2D', fontsize=12) mp.tight_layout() mp.show()
def plot_confusion_matrix(y_true, y_pred, title=None, normalize=False, ax=None): """Generates confusion matrix plot for a given set of ground truth labels and classifier predictions. Args: y_true (array-like, shape (n_samples)): Ground truth (correct) target values. y_pred (array-like, shape (n_samples)): Estimated targets as returned by a classifier. title (string, optional): Title of the generated plot. Defaults to "Confusion Matrix" if `normalize` is True. Else, defaults to "Normalized Confusion Matrix. normalize (bool, optional): If True, normalizes the confusion matrix before plotting. Defaults to False. ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to plot the learning curve. If None, the plot is drawn on a new set of axes. Returns: ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was drawn. Example: >>> import scikitplot.plotters as skplt >>> rf = RandomForestClassifier() >>> rf = rf.fit(X_train, y_train) >>> y_pred = rf.predict(X_test) >>> skplt.plot_confusion_matrix(y_test, y_pred, normalize=True) <matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490> >>> plt.show() .. image:: _static/examples/plot_confusion_matrix.png :align: center :alt: Confusion matrix """ if ax is None: fig, ax = plt.subplots(1, 1) cm = confusion_matrix(y_true, y_pred) classes = np.unique(y_true) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] cm = np.around(cm, decimals=2) if title: ax.set_title(title) elif normalize: ax.set_title('Normalized Confusion Matrix') else: ax.set_title('Confusion Matrix') image = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) plt.colorbar(mappable=image) tick_marks = np.arange(len(classes)) ax.set_xticks(tick_marks) ax.set_xticklabels(classes) ax.set_yticks(tick_marks) ax.set_yticklabels(classes) thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): ax.text(j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") ax.set_ylabel('True label') ax.set_xlabel('Predicted label') return ax
def show_as_image(sample): bitmap = sample.reshape((13, 8)) plt.figure() plt.imshow(bitmap, cmap='gray', interpolation='nearest') plt.colorbar() plt.show()
# Select the 0th row: digit digit = samples[0,:] # Print digit print(digit) # Reshape digit to a 13x8 array: bitmap bitmap = digit.reshape(13,8) # Print bitmap print(bitmap) # Use plt.imshow to display bitmap plt.imshow(bitmap, cmap='gray', interpolation='nearest') plt.colorbar() plt.show() ################## def show_as_image(sample): bitmap = sample.reshape((13, 8)) plt.figure() plt.imshow(bitmap, cmap='gray', interpolation='nearest') plt.colorbar() plt.show() # Import NMF from sklearn.decomposition import NMF
def plot_current_field(self, xlim=None, flim=None, log=False, wrap_order=0): beam = self # XXX Not sure why I have to copy, I suspect the fft e = np.copy(beam.e[int(self.Nt / 2), :, :]) I = beam.intensity_from_field(e) If = abs(fftshift(beam.fft(e)))**2 fx, fy = beam.get_f() fx = fftshift(fx) fy = fftshift(fy) phase = np.angle(e) # Images X = beam.X Y = beam.Y ext = [-X / 2, X / 2, -Y / 2, Y / 2] extf = [fx[0], fx[-1], fy[0], fy[-1]] plt.figure(figsize=(16, 4), dpi=150) plt.subplot(131) plt.imshow(beam.prep_data(I), aspect='auto', extent=ext, cmap='viridis') cb = plt.colorbar() cb.set_label(r'Intensity ($10^{14}$ W/cm^2)') plt.xlabel(r'$x$ (um)') plt.ylabel(r'$y$ (um)') if xlim != None: plt.xlim(xlim) plt.ylim(xlim) if wrap_order == 0: axis0 = 0 axis1 = 1 elif wrap_order == 1: axis0 = 1 axis1 = 0 plt.subplot(132) plt.imshow(np.unwrap(np.unwrap(beam.prep_data(phase), axis=axis0), axis=axis1), aspect='auto', extent=ext, cmap='viridis') cb = plt.colorbar() cb.set_label(r'Phase (rad)') plt.xlabel(r'$x$ (um)') plt.ylabel(r'$y$ (um)') if xlim != None: plt.xlim(xlim) plt.ylim(xlim) plt.subplot(133) plt.imshow(beam.prep_data(If), aspect='auto', extent=extf, cmap='viridis') cb = plt.colorbar() cb.set_label(r'Intensity (arb unit)') plt.xlabel(r'$f_x$ (um$^{-1}$)') plt.ylabel(r'$f_y$ (um$^{-1}$)') if flim != None: plt.xlim(flim) plt.ylim(flim) plt.tight_layout() plt.show() # Lineouts # We've already taken the transpose so y is the first index indy = int(beam.Ny / 2) indx = int(beam.Nx / 2) x = beam.x y = beam.y plt.figure(figsize=(16, 4), dpi=150) plt.subplot(131) plt.plot(x, I[:, indy], label='y') plt.plot(y, I[indx, :], 'm--', label='x') plt.legend() plt.xlabel(r'$x$ (um)') plt.ylabel(r'Intensity ($10^{14}$ W/cm^2)') if xlim != None: plt.xlim(xlim) plt.subplot(132) plt.plot(x, np.unwrap(phase[:, indy]), label='x') plt.plot(y, np.unwrap(phase[indx, :]), 'm--', label='y') plt.legend() plt.xlabel(r'$x$ (um)') plt.ylabel(r'Phase (rad)') if xlim != None: plt.xlim(xlim) plt.subplot(133) plt.plot(fx, If[:, indy], label='x') plt.plot(fy, If[indx, :], 'm--', label='y') plt.legend() plt.xlabel(r'$f_x$ (um$^{-1}$)') plt.ylabel(r'Intensity (arb unit)') if flim != None: plt.xlim(flim) plt.tight_layout() plt.show() if log == True: # Lineouts plt.figure(figsize=(16, 4), dpi=150) plt.subplot(131) plt.plot(x, I[:, indy], label='x') plt.plot(y, I[indx, :], 'm--', label='y') plt.legend() plt.xlabel(r'$x$ (um)') plt.ylabel(r'Intensity ($10^{14}$ W/cm^2)') plt.yscale('log') if xlim != None: plt.xlim(xlim) plt.subplot(132) plt.plot(x, np.unwrap(phase[:, indy]), label='x') plt.plot(y, np.unwrap(phase[indx, :]), 'm--', label='y') plt.legend() plt.xlabel(r'$x$ (um)') plt.ylabel(r'Phase (rad)') plt.yscale('log') if xlim != None: plt.xlim(xlim) plt.subplot(133) plt.plot(fx, If[:, indy], label='x') plt.plot(fy, If[indx, :], 'm--', label='y') plt.legend() plt.xlabel(r'$f_x$ (um$^{-1}$)') plt.ylabel(r'Intensity (arb unit)') plt.yscale('log') if flim != None: plt.xlim(flim) plt.tight_layout() plt.show()
async def poisson( self, interaction: discord.Interaction, team1: str, team2: str, num_games: int = 5, image: bool = False ): """Predicts a series between two teams using a poisson process Args: team1 (str): Team name team2 (str): Team name numGames (int, optional): Number of games in the series (up to 15 games) image (bool, optional): Whether or not to include a visualization of the poisson distribution """ async with interaction.channel.typing(): await interaction.response.defer() team1 = team1.title() team2 = team2.title() try: league = self.identifier.find_league(team1) except TypeError: return await interaction.followup.send(f"Could not understand team: {team1}", ephemeral = True) try: if league != self.identifier.find_league(team2): return await interaction.followup.send("Teams must be from the same league", ephemeral = True) except TypeError: return await interaction.followup.send(f"Couldn't understand team: {team2}") if num_games > 15: return await interaction.followup.send("To avoid spam and rate limiting, 15 is the maximum number of games supported.", ephemeral = True) handler = self.poissonHandler if image: img: AxesImage = plt.imshow( handler.generatePoisson(team1, team2, league)[0] ) plt.title(f"Poisson Distribution: {team1} vs. {team2}", fontsize=16) cb = plt.colorbar(img, label="Probability of result") plt.xlabel(f"{team1} Goals", fontsize=10) plt.ylabel(f"{team2} Goals", fontsize=10) img.figure.savefig("poisson.png", bbox_inches="tight") cb.remove() # Remove the colorbar so that it doesn't stay for the next function call path = os.path.abspath("poisson.png") file = discord.File(path) await interaction.followup.send(file=file) file.close() os.remove(path) if not interaction.response.is_done(): await interaction.followup.send(f"{team1} vs. {team2}") team1Poisson, team2Poisson = handler.getOneWayPoisson(league, team1, team2) team1Wins = 0 team2Wins = 0 i = 1 while i <= num_games: team1Goals = np.random.choice([0, 1, 2, 3, 4, 5], p=team1Poisson) team2Goals = np.random.choice([0, 1, 2, 3, 4, 5], p=team2Poisson) if team1Goals == team2Goals: # Redo this loop if tied continue elif team1Goals > team2Goals: await interaction.channel.send( f"**Game {i} result:** {team1} {team1Goals} - {team2Goals} {team2}" ) team1Wins += 1 elif team2Goals > team1Goals: await interaction.channel.send( f"**Game {i} result:** {team2} {team2Goals} - {team1Goals} {team1}" ) team2Wins += 1 i += 1 if team1Wins > (num_games / 2): return await interaction.channel.send( f"{team1} has won the series with a score of {team1Wins} - {team2Wins}" ) elif team2Wins > (num_games / 2): return await interaction.channel.send( f"{team2} has won the series with a score of {team2Wins} - {team1Wins}" ) return await interaction.channel.send( f"The series has ended in a {team1Wins} - {team2Wins} draw. Consider using an odd number of games" )
import numpy as np import matplotlib.pyplot as plt #image_data a = np.array([ 0.313660827978, 0.365348418405, 0.423733120134, 0.365348418405, 0.439599930621, 0.525083754405, 0.423733120134, 0.525083754405, 0.651536351379 ]).reshape(3, 3) plt.imshow(a, interpolation='nearest', cmap='bone', origin='upper') #upper lower plt.colorbar(shrink=0.9) plt.xticks(()) plt.yticks(()) plt.show()
Jcvc_opt = np.load(fname2+"/Jcvc_opt.npy") Jcve_opt = np.load(fname2+"/Jcve_opt.npy") Lmc = np.load(fname2+"/Lmc.npy") Lme = np.load(fname2+"/Lme.npy") nuc_opt = np.load(fname2+"/nuc_opt.npy") nue_opt = np.load(fname2+"/nue_opt.npy") chic_opt = np.load(fname2+"/chic_opt.npy") chie_opt = np.load(fname2+"/chie_opt.npy") Jhis[Jhis>=0.5] = 0.5 plt.figure() X,Y = np.meshgrid(ahis,ehis) cp = plt.contourf(X,Y,Jhis,20) #.clabel(cp,colors="white",fmt="%2.1f",fontsize=13) cb = plt.colorbar(cp) cb.set_label("optimal estimation error",fontsize=LabelSize) cb.set_ticks([0.378,0.396,0.414,0.432,0.450,0.468,0.486,0.500]) cb.set_ticklabels([r"0.378",r"0.396",r"0.414",r"0.432",r"0.450",r"0.468",r"0.486",r"$\geq 0.500$"]) plt.xlabel(r"contraction rate $\alpha$",fontsize=LabelSize) plt.ylabel(r"design parameter $\varepsilon$",fontsize=LabelSize) #plt.title(tit1,fontsize=FontSize) fname = "figs/alpeps.pdf" plt.savefig(fname,bbox_inches='tight',dpi=DPI) plt.show() data1 = {'score': np.sum((xhis-zhis)**2,1)} data2 = {'score': np.sum((x2his-z2his)**2,1)} data3 = {'score': np.sum((x3his-z3his)**2,1)} data4 = {'score': np.sum((x4his-z4his)**2,1)}
def sufficient_summary(y, f, out_label=None, opts=None): """Make a summary plot with the given predictors and responses. Parameters ---------- y : ndarray M-by-1 or M-by-2 matrix that contains the values of the predictors for the summary plot. f : ndarray M-by-1 matrix that contains the corresponding responses out_label : str, optional a label for the quantity of interest (default None) opts : dict, optional a dictionary with some plot options (default None) Notes ----- If `y.shape[1]` is 1, then this function produces only the univariate summary plot. If `y.shape[1]` is 2, then this function produces both the univariate and the bivariate summary plot, where the latter is a scatter plot with the first column of `y` on the horizontal axis, the second column of `y` on the vertical axis, and the color corresponding to `f`. """ if opts == None: opts = plot_opts() # check sizes of y n = y.shape[1] if n == 1: y1 = y elif n == 2: y1 = y[:,0] y2 = y[:,1] else: raise Exception('Sufficient summary plots cannot be made in more than 2 dimensions.') # set labels for plots if out_label is None: out_label = 'Output' plt.figure(figsize=(7,7)) plt.rc('font', **opts['myfont']) plt.plot(y1, f, 'bo', markersize=12) plt.xlabel('Active variable') plt.ylabel(out_label) plt.grid(True) if opts['savefigs']: figname = 'figs/ssp1_' + out_label + opts['figtype'] plt.savefig(figname, dpi=300, bbox_inches='tight', pad_inches=0.0) if n==2: plt.figure(figsize=(7,7)) plt.rc('font', **opts['myfont']) plt.scatter(y1, y2, c=f, s=150.0, vmin=np.min(f), vmax=np.max(f)) plt.xlabel('Active variable 1') plt.ylabel('Active variable 2') ymin = 1.1*np.amin([np.amin(y1), np.amin(y2)]) ymax = 1.1*np.amax([np.amax(y1), np.amax(y2)]) plt.axis([ymin, ymax, ymin, ymax]) plt.axes().set_aspect('equal') plt.grid(True) plt.title(out_label) plt.colorbar() if opts['savefigs']: figname = 'figs/ssp2_' + out_label + opts['figtype'] plt.savefig(figname, dpi=300, bbox_inches='tight', pad_inches=0.0) show_plot(plt)
rz = 20 * np.ones(nr) recs = np.vstack((rx, rz)) dr = recs[0, 1] - recs[0, 0] # Sources ns = 10 sx = np.linspace(dx * 10, (nx - 10) * dx, ns) sz = 10 * np.ones(ns) sources = np.vstack((sx, sz)) ds = sources[0, 1] - sources[0, 0] plt.figure(figsize=(10, 5)) im = plt.imshow(vel.T, cmap="gray", extent=(x[0], x[-1], z[-1], z[0])) plt.scatter(recs[0], recs[1], marker="v", s=150, c="b", edgecolors="k") plt.scatter(sources[0], sources[1], marker="*", s=150, c="r", edgecolors="k") plt.colorbar(im) plt.axis("tight") plt.xlabel("x [m]"), plt.ylabel("y [m]") plt.title("Velocity") plt.xlim(x[0], x[-1]) plt.figure(figsize=(10, 5)) im = plt.imshow(refl.T, cmap="gray", extent=(x[0], x[-1], z[-1], z[0])) plt.scatter(recs[0], recs[1], marker="v", s=150, c="b", edgecolors="k") plt.scatter(sources[0], sources[1], marker="*", s=150, c="r", edgecolors="k") plt.colorbar(im) plt.axis("tight") plt.xlabel("x [m]"), plt.ylabel("y [m]") plt.title("Reflectivity") plt.xlim(x[0], x[-1])
A_B = np.r_[A[:select], B[:select]] ###################################################################### # Before training, the separation between the classes is not recognizable # in the Gram matrix: # gram_before = [[overlaps(init_pars, X1=[x1], X2=[x2]) for x1 in A_B] for x2 in A_B] ax = plt.subplot(111) im = ax.matshow(gram_before, vmin=0, vmax=1) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax) plt.show() ###################################################################### # After training, the gram matrix clearly separates the two classes. # gram_after = [[overlaps(pretrained_pars, X1=[x1], X2=[x2]) for x1 in A_B] for x2 in A_B] ax = plt.subplot(111) im = ax.matshow(gram_after, vmin=0, vmax=1) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax) plt.show()
data_set = pd.read_csv('Rap.csv') # Считываем данные SCV-файла с DataSet'ом bpm = data_set['bpm'] # Переменная для параметра BPM в каждой строке year = data_set['year'] # Переменная для параметра "год релиза" в каждой строке plt.scatter( # Построение точечного графика и его настройка bpm, year, c=bpm, s=bpm*1.5, cmap='gist_heat', edgecolor='black', linewidth=.7 ) bar = plt.colorbar( # Построение шкалы BPM orientation='horizontal', shrink=0.8, extend='both', extendfrac=.1 ) bar.set_label('Шкала ударов в минуту', fontsize=18) # Подпись шкалы plt.title('Популярность скорости ' # Заголовок графика 'исполнения в Rap\'е ', fontsize=25) plt.xlabel('BPM', fontsize=18) # Ось абсцисс plt.ylabel('Год релиза', fontsize=18) # Ось ординат plt.tight_layout() # Настройка параметров подзаголовков в области отображения plt.show() # Вывод на экран
# 加载数据集 feature=np.load('./checkpoints/20190424-2211/max/feature_fcgan.npy') #feature=np.random.rand(20000,100) t_features=[] t_labels=[] for i in range(len(randIdx)): t_features.append(feature[randIdx[i]]) t_labels.append(y_labels[randIdx[i]]) #print(t_feature.sum()) print(np.shape(t_features)) print(np.shape(t_labels)) iris = load_iris() # 共有150个例子, 数据的类型是numpy.ndarray print(iris.data.shape) # 对应的标签有0,1,2三种 print(iris.target) # 使用TSNE进行降维处理。从4维降至2维。 #tsne = TSNE(n_components=2, learning_rate=100).fit_transform(feature) tsne = TSNE(n_components=2, learning_rate=100).fit_transform(t_features) # 使用PCA 进行降维处理 pca = PCA().fit_transform(t_features) # 设置画布的大小 plt.figure(figsize=(12, 6)) plt.subplot(121) plt.scatter(tsne[:, 0], tsne[:, 1], c=t_labels) plt.subplot(122) plt.scatter(pca[:, 0], pca[:, 1], c=t_labels) plt.colorbar()#使用这一句就可以分辨出,颜色对应的类了!神奇啊。 plt.savefig('plot.pdf')
# Plot up the 'Old-Fashioned Way' - Using matplotlib.pyplot pcolormesh import numpy as np fig = plt.figure(figsize=(16, 12)) ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) ax.set_extent((-100, -60, 16, 52), crs=ccrs.PlateCarree()) im = ax.pcolormesh(oceanSST['longitude'].values, oceanSST['latitude'].values, oceanSST['Band15'][0].values, cmap='jet', transform=ccrs.PlateCarree(), vmin=250, vmax=300) ax.add_feature(cf.COASTLINE) ax.add_feature(cf.BORDERS) plt.colorbar(im, label="Degrees Kelvin") # Plot lat / lon ticks plt.xticks( np.arange(np.min(oceanSST['longitude'].values), np.max(oceanSST['longitude'].values), 10)) plt.yticks( np.arange(np.min(oceanSST['latitude'].values), np.max(oceanSST['latitude'].values), 10)) # Plot x/y labels plt.xlabel("Longitude") plt.ylabel("Latitude") # Plot Title plt.title("Band 15 Brightness Temperature") # What about SST? # This time we'll plot with the handy-dandy xarray plotting function
def plot_confusion_matrix(phase, path, class_names): """Plots the confusion matrix using matplotlib. Parameter --------- phase : str String value indicating for what phase is the confusion matrix, i.e. training/validation/testing path : str Directory where the predicted and actual label NPY files reside class_names : str List consisting of the class names for the labels Returns ------- conf : array, shape = [num_classes, num_classes] Confusion matrix accuracy : float Predictive accuracy """ # list all the results files files = list_files(path=path) labels = np.array([]) for file in files: labels_batch = np.load(file) labels = np.append(labels, labels_batch) if (files.index(file) / files.__len__()) % 0.2 == 0: print("Done appending {}% of {}".format( (files.index(file) / files.__len__()) * 100, files.__len__())) labels = np.reshape(labels, newshape=(labels.shape[0] // 4, 4)) print("Done appending NPY files.") # get the predicted labels predictions = labels[:, :2] # get the actual labels actual = labels[:, 2:] # create a TensorFlow session with tf.Session() as sess: # decode the one-hot encoded labels to single integer predictions = sess.run(tf.argmax(predictions, 1)) actual = sess.run(tf.argmax(actual, 1)) # get the confusion matrix based on the actual and predicted labels conf = confusion_matrix(y_true=actual, y_pred=predictions) # create a confusion matrix plot plt.imshow(conf, cmap=plt.cm.Purples, interpolation="nearest") # set the plot title plt.title("Confusion Matrix for {} Phase".format(phase)) # legend of intensity for the plot plt.colorbar() tick_marks = np.arange(len(class_names)) plt.xticks(tick_marks, class_names, rotation=45) plt.yticks(tick_marks, class_names) plt.tight_layout() plt.ylabel("Actual label") plt.xlabel("Predicted label") # show the plot plt.show() # get the accuracy of the phase accuracy = (conf[0][0] + conf[1][1]) / labels.shape[0] # return the confusion matrix and the accuracy return conf, accuracy
def plot(): detName = "conf/P42574A_grad%0.2f_pcrad%0.2f_pclen%0.2f.conf" % (0.05, 2.5, 1.65) det = Detector(detName, timeStep=1, numSteps=10) data = np.loadtxt("posterior_sample.txt") num_samples = len(data) print "found %d samples" % num_samples r_arr = np.empty(num_samples) z_arr = np.empty(num_samples) h_100_mu0 = np.empty(num_samples) h_100_beta = np.empty(num_samples) h_100_e0 = np.empty(num_samples) h_111_mu0 = np.empty(num_samples) h_111_beta = np.empty(num_samples) h_111_e0 = np.empty(num_samples) tf = np.empty((6, num_samples)) for (idx, params) in enumerate(data): rad, phi, theta, scale, t0, smooth = params[:6] r_arr[idx] = rad * np.cos(theta) z_arr[idx] = rad * np.sin(theta) h_100_mu0[idx], h_100_beta[idx], h_100_e0[idx], h_111_mu0[ idx], h_111_beta[idx], h_111_e0[idx] = params[ velo_first_idx:velo_first_idx + 6] tf[:, idx] = params[tf_first_idx:tf_first_idx + 6] positionFig = plt.figure(0) plt.clf() xedges = np.linspace(0, np.around(det.detector_radius, 1), np.around(det.detector_radius, 1) * 10 + 1) yedges = np.linspace(0, np.around(det.detector_length, 1), np.around(det.detector_length, 1) * 10 + 1) plt.hist2d(r_arr, z_arr, norm=LogNorm(), bins=[xedges, yedges]) plt.colorbar() plt.xlabel("r from Point Contact (mm)") plt.ylabel("z from Point Contact (mm)") plotnum = 600 veloFig = plt.figure(1) tf0 = veloFig.add_subplot(plotnum + 11) tf1 = veloFig.add_subplot(plotnum + 12, ) tf2 = veloFig.add_subplot(plotnum + 13, ) tf3 = veloFig.add_subplot(plotnum + 14, ) tf4 = veloFig.add_subplot(plotnum + 15, ) tf5 = veloFig.add_subplot(plotnum + 16, ) tf0.set_ylabel('h_100_mu0') tf1.set_ylabel('h_100_beta') tf2.set_ylabel('h_100_e0') tf3.set_ylabel('h_111_mu0') tf4.set_ylabel('h_111_beta') tf5.set_ylabel('h_111_e0') num_bins = 100 [n, b, p] = tf0.hist(h_100_mu0, bins=num_bins) [n, b, p] = tf1.hist(h_100_beta, bins=num_bins) [n, b, p] = tf2.hist(h_100_e0, bins=num_bins) [n, b, p] = tf3.hist(h_111_mu0, bins=num_bins) [n, b, p] = tf4.hist(h_111_beta, bins=num_bins) [n, b, p] = tf5.hist(h_111_e0, bins=num_bins) plotnum = 600 tfFig = plt.figure(2) tf0 = tfFig.add_subplot(plotnum + 11) tf1 = tfFig.add_subplot(plotnum + 12, ) tf2 = tfFig.add_subplot(plotnum + 13, ) tf3 = tfFig.add_subplot(plotnum + 14, ) tf4 = tfFig.add_subplot(plotnum + 15, ) tf5 = tfFig.add_subplot(plotnum + 16, ) tf0.set_ylabel('b_ov_a') tf1.set_ylabel('c') tf2.set_ylabel('d') tf3.set_ylabel('rc1') tf4.set_ylabel('rc2') tf5.set_ylabel('rcfrac') num_bins = 100 [n, b, p] = tf0.hist(tf[0, :], bins=num_bins) [n, b, p] = tf1.hist(tf[1, :], bins=num_bins) [n, b, p] = tf2.hist(tf[2, :], bins=num_bins) [n, b, p] = tf3.hist(tf[3, :], bins=num_bins) [n, b, p] = tf4.hist(tf[4, :], bins=num_bins) [n, b, p] = tf5.hist(tf[5, :], bins=num_bins) plt.show()
format='%.0e') #plt.contourf(x,y,data,ticks3,norm=colors.LogNorm(vmin=1e-5,vmax=8e4),cmap='RdYlBu_r', format = '%.0e') #plt.contourf(x,y,data,ticks3,norm=colors.LogNorm(vmin=pow(10,1),vmax=pow(10,6)),cmap=plt.cm.jet,resolution='c', format = '%.0e') #plt.clim((pow(10,3),pow(10,7))) plt.plot(lat1, trop_height.data, 'k--') mn = 0.1 mx = 100000 md = (mx - mn) / 2 print('\nThe maximum value of particle number is = ', np.max(data)) print('\nThe mean value of particle number at 11.5km = ', np.mean(data[39, :]), '\n') #plt.contourf(x,y,data,cmap=,resolution='c') formatter = LogFormatter(10, labelOnlyBase=False) cbar = plt.colorbar() #cbar=plt.colorbar(ticks=ticks3, format=formatter) #cbar.set_ticks(ticks4) cbar.set_ticks(ticks5) #ticks3=['1','5','10','20','50','1E2','2e2','5e2','1e3','2e3','5e3','1e4','3e4','6e4','1e5','2e5'] cbar.set_ticklabels(ticks5_label) #cbar.set_ticklabels(ticks3_label) #plt.yticks(['1','10']) #plt.clim((pow(10,3),pow(10,7))) plt.xlabel('latitude') plt.ylabel('altitude (km)') #plt.title('Total Particle number concentration (cm'+u'\u207B\u00B3'+')') plt.title('Change in Particle number concentration (cm' + u'\u207B\u00B3' + ') - PD')
def plot_event(self, event): self.event = event self.fig = plt.figure(figsize=(15, 12)) x_pad = 0.04 y_pad = 0.05 extra_y_pad_top = -0.02 extra_x_pad_left = 0.02 y_sep_middle = 0.06 start_x = x_pad + extra_x_pad_left start_y = y_pad full_x = 1 - x_pad - start_x full_y = 1 - y_pad - start_y - y_sep_middle - extra_y_pad_top row_y = full_y / 4 column_x = full_y / 4 title = 'Event %s from %s' % (event.event_number, event.dataset_name) plt.suptitle(title, fontsize=16, horizontalalignment='right', x=0.99) ## # Channel waveforms plot ## self.channel_wv_ax = plt.axes([start_x, start_y, full_x, row_y]) q = PlotChannelWaveforms2D(self.config, self.processor) q.plot_event(event, ax=self.channel_wv_ax) self.chwvs_2s_time_scale = q.time_scale # TODO: Make top, bottom, veto yticks on right y axis? ## # Event waveform plot ## event_wv_ax = plt.axes([start_x, start_y + row_y, full_x, row_y], sharex=self.channel_wv_ax) q = PlotSumWaveformEntireEvent(self.config, self.processor) q.plot_event(event, show_legend=True, ax=event_wv_ax) event_wv_ax.get_xaxis().set_visible(False) ## # Whereami plot ## whereami_height = 0.01 self.whereami_ax = plt.axes( [start_x, start_y + 2 * row_y, full_x, whereami_height], sharex=self.channel_wv_ax) self.whereami_ax.set_axis_off() ## # Event and peak text ## x_sep_text = 0.07 y_sep_text = 0.05 x = start_x + 2 * column_x + x_sep_text y = start_y + 4 * row_y + y_sep_middle - y_sep_text event_text = '' event_text += 'Event recorded at %s UTC, %09d ns\n' % ( epoch_to_human_time( self.trigger_time_ns), self.trigger_time_ns % units.s) # suspicious_channels = np.where(event.is_channel_suspicious)[0] # event_text += 'Suspicious channels (# hits rejected):\n ' + ', '.join([ # '%s (%s)' % (ch, event.n_hits_rejected[ch]) for ch in suspicious_channels]) + '\n' self.fig.text(x, y, self.wrap_multiline(event_text, self.max_characters), verticalalignment='top') self.peak_text = self.fig.text(x, start_y + 3 * row_y + y_sep_middle, '', verticalalignment='top') ## # Peak hitpatterns ## y = start_y + 2 * row_y + y_sep_middle self.bot_hitp_ax = plt.axes([start_x, y, column_x, row_y]) self.top_hitp_ax = plt.axes([start_x, y + row_y, column_x, row_y], sharex=self.bot_hitp_ax) self.top_hitp_ax.get_xaxis().set_visible(False) ## # Get the TPC peaks ## # Did the user specify a peak number? If so, get it self.peak_i = self.starting_peak_per_event.get(event.event_number, None) self.peaks = event.get_peaks_by_type(detector='tpc', sort_key='left', reverse=False) self.peaks = [p for p in self.peaks if p.type != 'lone_hit'] if len(self.peaks) == 0: self.log.debug( "No peaks in this event, will be a boring peakviewer plot...") return event ## # Peak Waveforms ## x_sep = 0.03 x = start_x + column_x + x_sep self.peak_chwvs_ax = plt.axes([x, y, column_x - x_sep, row_y]) self.peak_chwvs_ax.yaxis.tick_right() self.peak_chwvs_ax.yaxis.set_label_position("right") self.peak_sumwv_ax = plt.axes([x, y + row_y, column_x - x_sep, row_y], sharex=self.peak_chwvs_ax) self.peak_sumwv_ax.yaxis.tick_right() self.peak_sumwv_ax.yaxis.set_label_position("right") self.peak_sumwv_ax.get_xaxis().set_visible(False) q = PlotChannelWaveforms2D(self.config, self.processor) q.plot_event(event, ax=self.peak_chwvs_ax, show_channel_group_labels=False) ## # Buttons ## x = start_x + 2 * column_x + x_sep button_width = 0.08 button_height = 0.03 buttons_x_space = 0.04 self.make_button([x, y, button_width, button_height], 'Prev peak', self.draw_prev_peak) self.make_button([x + button_width, y, button_width, button_height], 'Next peak', self.draw_next_peak) self.make_button([ x + 2 * button_width + buttons_x_space, y, button_width, button_height ], 'Main S1', self.draw_main_s1) self.make_button([ x + 3 * button_width + buttons_x_space, y, button_width, button_height ], 'Main S2', self.draw_main_s2) ## # Select and draw the desired peak ## if event.event_number in self.starting_peak_per_event: # The user specified the left boundary of the desired starting peak desired_left = self.starting_peak_per_event[event.event_number] self.peak_i = np.argmin( [np.abs(p.left - desired_left) for p in self.peaks]) if self.peaks[self.peak_i].left != desired_left: self.log.warning( 'There is no (tpc, non-lone-hit) peak starting at index %d! ' 'Taking closest peak (%d-%d) instead.' % (desired_left, self.peaks[self.peak_i].left, self.peaks[self.peak_i].right)) self.log.debug("Selected user-defined peak %d" % self.peak_i) self.draw_peak() elif self.starting_peak == 'first': self.peak_i = 0 self.draw_peak() elif self.starting_peak == 'main_s1': self.draw_main_s1() elif self.starting_peak == 'main_s2': self.draw_main_s2() if self.peak_i is None: # Either self.starting_peak is 'largest' or one of the other peak selections failed # (e.g. couldn't draw the main s1 because there is no S1) # Just pick the largest peak (regardless of its type) self.peak_i = np.argmax([p.area for p in self.peaks]) self.log.debug("Largest peak is %d (peak list runs from 0-%d)" % (self.peak_i, len(self.peaks) - 1)) self.draw_peak() # Draw the color bar for the top or bottom hitpattern plot (they share them) # In the rare case the top has no data points, take it from the bottom sc_for_hitp = self.top_hitp_sc if self.peaks[ self.peak_i].area_fraction_top != 0 else self.bot_hitp_sc plt.colorbar(sc_for_hitp, ax=[self.top_hitp_ax, self.bot_hitp_ax])
r_max, g_r_max = find_local_maxima(r, g_r_t[j], r_guess=0.45) plt.plot(r_max, g_r_max, 'k.') plt.plot(r, g_r_t[j], label='{:.3f} ps'.format(t[j])) # Save output to text files np.savetxt('vhf.txt', g_r_t) np.savetxt('r.txt', r) np.savetxt('t.txt', t) ax.set_xlim((0, 0.8)) ax.set_ylim((0, 3.0)) ax.legend(loc=0) ax.set_xlabel(r'Radial coordinate, $r$, $nm$') ax.set_ylabel(r'Van Hove Function, , $g(r, t)$, $unitiless$') plt.savefig('van-hove-function.pdf') fig, ax = plt.subplots() heatmap = ax.imshow(g_r_t-1, vmin=-0.04, vmax=0.04, cmap='RdYlGn_r', origin='lower', extent=(r[0], r[-1], t[0], t[-1])) ax.grid(False) ax.set_xlabel(r'Radial position, $r$, $nm$') ax.set_ylabel(r'Time, $t$, $ps$') colorbar = plt.colorbar(heatmap) colorbar.set_label(r'$g(r, t) - 1$', rotation=270) fig.savefig('heatmap.pdf')
def plot_hex_map(d_matrix, titles=[], colormap=cm.gray, shape=[1, 1], comp_width=5, hex_shrink=1.0, fig=None, colorbar=True): """ Plot hexagon map where each neuron is represented by a hexagon. The hexagon color is given by the distance between the neurons (D-Matrix) Args: - grid: Grid dictionary (keys: centers, x, y ), - d_matrix: array contaning the distances between each neuron - w: width of the map in inches - title: map title Returns the Matplotlib SubAxis instance """ d_matrix = np.flip(d_matrix, axis=0) def create_grid_coordinates(x, y): coordinates = [ x for row in -1 * np.array(list(range(x))) for x in list( zip(np.arange(((row) % 2) * 0.5, y + ((row) % 2) * 0.5), [0.8660254 * (row)] * y)) ] return (np.array(list(reversed(coordinates))), x, y) if d_matrix.ndim < 3: d_matrix = np.expand_dims(d_matrix, 2) if len(titles) != d_matrix.shape[2]: titles = [""] * d_matrix.shape[2] n_centers, x, y = create_grid_coordinates(*d_matrix.shape[:2]) # Size of figure in inches if fig is None: xinch, yinch = comp_width * shape[1], comp_width * (x / y) * shape[0] fig = plt.figure(figsize=(xinch, yinch), dpi=72.) for comp, title in zip(range(d_matrix.shape[2]), titles): ax = fig.add_subplot(shape[0], shape[1], comp + 1, aspect='equal') # Get pixel size between two data points xpoints = n_centers[:, 0] ypoints = n_centers[:, 1] ax.scatter(xpoints, ypoints, s=0.0, marker='s') ax.axis([ min(xpoints) - 1., max(xpoints) + 1., min(ypoints) - 1., max(ypoints) + 1. ]) xy_pixels = ax.transData.transform(np.vstack([xpoints, ypoints]).T) xpix, ypix = xy_pixels.T # discover radius and hexagon apothem = hex_shrink * (xpix[1] - xpix[0]) / math.sqrt(3) area_inner_circle = math.pi * (apothem**2) dm = d_matrix[:, :, comp].reshape(np.multiply(*d_matrix.shape[:2])) collection_bg = RegularPolyCollection( numsides=6, # a hexagon rotation=0, sizes=(area_inner_circle, ), array=dm, cmap=colormap, offsets=n_centers, transOffset=ax.transData, ) ax.add_collection(collection_bg, autolim=True) ax.axis('off') ax.autoscale_view() ax.set_title(title) #, fontdict={"fontsize": 3 * comp_width}) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(collection_bg, cax=cax) if not colorbar: cbar.remove() #cbar.ax.tick_params(labelsize=3 * comp_width) return ax, list(reversed(n_centers))
def add_fault(c, velocity, fill_fault=True, plot=False): "add a fault to a velocity model" # fault parameters m_range = c.fm_m_range x0_range = c.fm_x0_range y0_range = c.fm_y0_range y_start_range = c.fm_y_start_range y_shift_range = c.fm_y_shift_range fault_width = c.fm_fault_width fault_velocity = c.fm_fault_velocity # sample distributions m = np.random.uniform(m_range[0], m_range[1]) if np.random.random() > 0.5: m *= -1 x0, y0 = (np.random.randint(x0_range[0], x0_range[1]), np.random.randint(y0_range[0], y0_range[1])) y_start = np.random.randint(y_start_range[0], y_start_range[1]) y_shift = -np.random.randint(y_shift_range[0], y_shift_range[1]) y_range = (y_start, y_start + velocity.shape[1]) if plot: print(m, (x0, y0), y_range, y_shift) # derived parameters c = y0 - m * x0 # for selecting slab masks delta_y = int(y_shift) # for actually shifting the fault (rounded) delta_x = int(np.round(y_shift / m)) # pad y by delta_y # pad x by delta_x # both these may over-pad (for code simplicity) pad_x, pad_y = np.abs(delta_x), np.abs(delta_y) v_pad = np.pad(np.copy(velocity), [(pad_x, pad_x), (pad_y, pad_y)], 'edge') # get fault block masks slab_mask = np.zeros(v_pad.shape) empty_mask = np.zeros(v_pad.shape) reverse = False if np.random.random() > 0.5: reverse = True for xval, col in enumerate(v_pad): for yval, _ in enumerate(col): if ((m * (xval - pad_x) + c < (yval - pad_y) and reverse) or (m * (xval - pad_x) + c > (yval - pad_y) and not reverse)): if (y_range[0] < (yval - pad_y) <= y_range[1]): slab_mask[xval, yval] = 1 # just fills slab if ((y_range[0] - pad_y) < (yval - pad_y) <= y_range[1]): empty_mask[xval, yval] = 1 # fills upwards to include delta_y # shift blocks slab = v_pad * slab_mask #order ensures no interpolation, origin is origin in original image (which is shifted to 0,0 in output) slab_shift = scipy.ndimage.affine_transform(slab, np.diag((1, 1)), (delta_x, delta_y), order=0) empty_mask_shift = scipy.ndimage.affine_transform(empty_mask, np.diag((1, 1)), (delta_x, delta_y), order=0) v_pad_shift = v_pad * (1 - empty_mask_shift) + slab_shift # fill zeros, by whatever is above slab found = False fill_value = np.mean(velocity) for yval in np.arange(v_pad.shape[1]): row = slab_mask[:, yval] for xval, val in enumerate(row): if val == 1 and yval != 0: fill_value = v_pad[xval, yval - 1] found = True break if found: break v_pad_fill = np.copy(v_pad_shift) for xval, col in enumerate(v_pad_shift): for yval, vval in enumerate(col): if vval == 0: v_pad_fill[xval, yval] = fill_value # add fault block x_fault = ((yval - pad_y - c) / m) if (fill_fault and y_range[0] < (yval - pad_y) <= (y_range[1] + pad_y) and (x_fault - fault_width < (xval - pad_x) <= x_fault + fault_width)): v_pad_fill[xval, yval] = fault_velocity # crop v_fill = v_pad_fill[pad_x:-pad_x, pad_y:-pad_y] # optionally plot if plot: x = np.arange(velocity.shape[0]) plt.figure() plt.imshow(velocity.T, vmin=0, vmax=3500) plt.colorbar() plt.plot(x, m * x + c) plt.scatter(x0, y0) plt.scatter((y_range[0] - c) / m, y_range[0]) plt.scatter((y_range[1] - y_shift - c) / m, y_range[1] - y_shift) plt.xlim(0, velocity.shape[0]) plt.ylim(velocity.shape[1], 0) x_pad = np.arange(v_pad.shape[0]) plt.figure() plt.imshow(v_pad.T, vmin=0, vmax=3500) plt.colorbar() plt.plot(x_pad, m * (x_pad - pad_x) + c + pad_y) plt.scatter(x0 + pad_x, y0 + pad_y) plt.xlim(0, v_pad.shape[0]) plt.ylim(v_pad.shape[1], 0) plt.figure() plt.imshow(slab_mask.T) plt.colorbar() plt.plot(x_pad, m * (x_pad - pad_x) + c + pad_y) plt.scatter(x0 + pad_x, y0 + pad_y) plt.xlim(0, v_pad.shape[0]) plt.ylim(v_pad.shape[1], 0) plt.figure() plt.imshow(empty_mask.T) plt.colorbar() plt.plot(x_pad, m * (x_pad - pad_x) + c + pad_y) plt.scatter(x0 + pad_x, y0 + pad_y) plt.xlim(0, v_pad.shape[0]) plt.ylim(v_pad.shape[1], 0) plt.figure() plt.imshow(slab_shift.T, vmin=0, vmax=3500) plt.colorbar() plt.plot(x_pad, m * (x_pad - pad_x) + c + pad_y) plt.scatter(x0 + pad_x, y0 + pad_y) plt.xlim(0, v_pad.shape[0]) plt.ylim(v_pad.shape[1], 0) plt.figure() plt.imshow(empty_mask_shift.T) plt.colorbar() plt.plot(x_pad, m * (x_pad - pad_x) + c + pad_y) plt.scatter(x0 + pad_x, y0 + pad_y) plt.xlim(0, v_pad.shape[0]) plt.ylim(v_pad.shape[1], 0) plt.figure() plt.imshow(v_pad_shift.T, vmin=0, vmax=3500) plt.colorbar() plt.plot(x_pad, m * (x_pad - pad_x) + c + pad_y) plt.scatter(x0 + pad_x, y0 + pad_y) plt.xlim(0, v_pad.shape[0]) plt.ylim(v_pad.shape[1], 0) plt.figure() plt.imshow(v_pad_fill.T, vmin=0, vmax=3500) plt.colorbar() plt.plot(x_pad, m * (x_pad - pad_x) + c + pad_y) plt.scatter(x0 + pad_x, y0 + pad_y) plt.xlim(0, v_pad.shape[0]) plt.ylim(v_pad.shape[1], 0) plt.figure() plt.imshow(v_fill.T, vmin=0, vmax=3500) plt.colorbar() plt.plot(x, m * x + c) plt.scatter(x0, y0) plt.scatter((y_range[0] - c) / m, y_range[0]) plt.scatter((y_range[1] - y_shift - c) / m, y_range[1] - y_shift) plt.xlim(0, velocity.shape[0]) plt.ylim(velocity.shape[1], 0) return v_fill
) processed_dataset = processor.apply_operations(dataset=dataset) # %% # The plot of the simulation. Because we configured the simulator object to simulate # spectrum per spin system, the following dataset is a CSDM object containing five # simulations (dependent variables). Let's visualize the first dataset corresponding to # :math:`\text{NiCl}_2\cdot 2 \text{D}_2\text{O}`. dataset_Ni = dataset.split()[0].real plt.figure(figsize=(4.25, 3.0)) ax = plt.subplot(projection="csdm") cb = ax.imshow(dataset_Ni / dataset_Ni.max(), aspect="auto", cmap="gist_ncar_r") plt.title(None) plt.colorbar(cb) plt.tight_layout() plt.show() # %% # The plot of the simulation after signal processing. proc_dataset_Ni = processed_dataset.split()[0].real plt.figure(figsize=(4.25, 3.0)) ax = plt.subplot(projection="csdm") cb = ax.imshow( proc_dataset_Ni / proc_dataset_Ni.max(), cmap="gist_ncar_r", aspect="auto" ) plt.title(None) plt.colorbar(cb)
from numpy import genfromtxt, shape from matplotlib.pyplot import figure, pcolormesh, streamplot, savefig, colorbar D = genfromtxt('salida.txt', delimiter=',') D = D[:, :-1] # Retirar ultima columna de nans n1, n2 = shape(D) # Contar datos # Separar datos n = int(n1 / 3) P = D[:n, :] Ex = D[n:2 * n, :] Ey = D[2 * n:3 * n, :] print(shape(P), shape(Ex), shape(Ey)) XY = genfromtxt('XY.txt', delimiter=',') XY = XY[:, :-1] # Retirar ultima columna de nans # Separar datos X = XY[:n, :] Y = XY[n:2 * n, :] print(shape(X), shape(Y)) figure() pcolormesh(X, Y, P) colorbar() streamplot(X, Y, Ex, Ey, density=1.5, color='k') savefig('placas.pdf')
BCoffset = int(xsize/20) # replacing all boundaries with nan to get location of vortices Usquare[0:BCoffset,:] = nan ; Usquare[:,0:BCoffset] = nan Usquare[xsize_max-BCoffset:xsize,:] = nan;Usquare[:,ysize_max-BCoffset:ysize] = nan Loc1_lbm = np.unravel_index(np.nanargmin(Usquare),Usquare.shape) # finding other vortices Usquare[Loc1_lbm[0]-offset2:Loc1_lbm[0]+offset2,Loc1_lbm[1]-offset2:Loc1_lbm[1]+offset2] = nan Loc2_lbm = np.unravel_index(np.nanargmin(Usquare),Usquare.shape) Usquare[Loc2_lbm[0]-offset2:Loc2_lbm[0]+offset2,Loc2_lbm[1]-offset2:Loc2_lbm[1]+offset2] = nan Loc3_lbm = np.unravel_index(np.nanargmin(Usquare),Usquare.shape) Usquare[Loc3_lbm[0]-offset2:Loc3_lbm[0]+offset2,Loc3_lbm[1]-offset2:Loc3_lbm[1]+offset2] = nan Loc4_lbm = np.unravel_index(np.nanargmin(Usquare),Usquare.shape) color1 = (np.sqrt(u_lbm[0,:,:]**2+u_lbm[1,:,:]**2)/uLB ).transpose() strm = subplot1.streamplot(XNorm,YNorm,(u_lbm[0,:,:]).transpose(),(u_lbm[1,:,:]).transpose(), color =color1,cmap=pyplot.cm.jet)#,norm=matplotlib.colors.Normalize(vmin=0,vmax=1)) cbar = pyplot.colorbar(strm.lines, ax = subplot1) subplot1.plot(Loc1_lbm[0]/xsize,(ysize_max-Loc1_lbm[1])/ysize,'mo', label='Vortex1') subplot1.plot(Loc2_lbm[0]/xsize,(ysize_max-Loc2_lbm[1])/ysize,'mo', label='Vortex2') subplot1.plot(Loc3_lbm[0]/xsize,(ysize_max-Loc3_lbm[1])/ysize,'mo', label='Vortex2') subplot1.plot(Loc4_lbm[0]/xsize,(ysize_max-Loc4_lbm[1])/ysize,'mo', label='Vortex2') subplot1.plot(X_Vor, Y_Vor,'rs', label='Ghia',alpha=1) subplot1.set_title('Velocity Streamlines - LBM', fontsize = 23, y =1.02) subplot1.margins(0.005) #subplot3.axis('tight') subplot1.set_xlabel('X-position', fontsize = 20);subplot1.set_ylabel('Y-position', fontsize = 20) color2 = (np.sqrt(u[0,:,:]**2+u[1,:,:]**2)/uLB ).transpose() strm = subplot2.streamplot(XNorm,YNorm,(u[0,:,:]).transpose(),(u[1,:,:]).transpose(), color =color2,cmap=pyplot.cm.jet)#,norm=matplotlib.colors.Normalize(vmin=0,vmax=1)) cbar = pyplot.colorbar(strm.lines, ax = subplot2) subplot2.plot(Loc1[0]/xsize,(ysize_max-Loc1[1])/ysize,'mo', label='Vortex1') subplot2.plot(Loc2[0]/xsize,(ysize_max-Loc2[1])/ysize,'mo', label='Vortex2') subplot2.plot(Loc3[0]/xsize,(ysize_max-Loc3[1])/ysize,'mo', label='Vortex2')
# axs[idx_plot].scatter(y_test, y_hat, s=1.7) nbins = 300 k = kde.gaussian_kde([y_test, y_hat]) xi, yi = np.mgrid[ y_test.min() : y_test.max() : nbins * 1j, y_hat.min() : y_hat.max() : nbins * 1j, ] zi = k(np.vstack([xi.flatten(), yi.flatten()])) im = axs[idx_plot].pcolormesh(xi, yi, zi.reshape(xi.shape), cmap="cividis") # e = f.colorbar(matplotlib.cm.ScalarMappable(), ax=axs[idx_plot]) fmt = matplotlib.ticker.ScalarFormatter() fmt.set_scientific(True) fmt.set_powerlimits((-2, 4)) plt.colorbar(im, ax=axs[idx_plot], format=fmt) axs[idx_plot].set_ylabel(f"Pred. {LABEL_GUIDE[data]}") axs[idx_plot].set_xlabel(f"Exp. {LABEL_GUIDE[data]}") # axs[idx_plot].grid(alpha=0.5) # cyp values y_test = [] y_hat = [] aucs = [] for idx_split in range(N_FOLDS): y = np.load( os.path.join(DATA_PATH, "cyp", f"cyp_noHs_y_fold{idx_split}.npy")
print(nc) for i in nc.variables: print(i, nc.variables[i].units, nc.variables[i].shape) lons = nc.variables['lon'][:] lats = nc.variables['lat'][:] time = nc.variables['time'][:] qv2m = nc.variables['qv_2m'][:] t_units = nc.variables['time'].units datevar = num2date(time[:], units='hours since 1970-01-01 00:00:00', calendar='standard') print(datevar[:]) map = Basemap(projection='merc', llcrnrlon=lons[0], llcrnrlat=lats[0], urcrnrlon=lons[599], urcrnrlat=lats[698], resolution='i') lon2, lat2 = np.meshgrid(lons, lats) x, y = map(lon2, lat2) my_cmap = plt.get_cmap('rainbow') plt.gca().set_axis_off() plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.margins(0, 0) map.pcolormesh(x, y, qv2m[0, :, :], cmap='rainbow_r') #plt.colorbar(label="2-m Mixing Ratio") # comment out later for b in range(0, 31): map.pcolormesh(x, y, qv2m[b, :, :], cmap='rainbow_r') #plt.title('2-m Mixing Ratio on %s' % datevar[b]) # comment out later cb = plt.colorbar(); cb.remove(); plt.draw(); plt.savefig("qv_2m_monthly_mean_d02_2009-2018_%s.png" % b, transparent='True', bbox_inches='tight', pad_inches=0) print('saved %s' % b)
print len(R) print len(Z) # Plot A #------------------------------------------------------------ plt.figure(figsize=(12, 8)) #plt.contourf(array with size x, array with size y, matrix with size x*y, Number of colors, choose a color map) plt.contourf(R, Z, Ca, NoColors, cmap=cmap) plt.xlim((xmin, xmax)) plt.ylim((ymin, ymax)) #plt.clim((0, 2)) plt.colorbar(format='%.1f') # plt.colorbar() plt.xlabel('R') plt.ylabel('Z') plt.title('Concentration A') plt.savefig('ConcentrationPlots/plot_ConcentrationA_.png') #plt.savefig('ConcentrationPlots/plot_ConcentrationA.eps') #plt.savefig('ConcentrationPlots/plot_ConcentrationA_' + str(frame) + '.pdf') # Plot B #------------------------------------------------------------ plt.figure(figsize=(12, 8)) plt.contourf(R, Z, Cb, NoColors, cmap=cmap)
def zonotope_2d_plot(vertices, design=None, y=None, f=None, out_label=None, opts=None): """A utility for plotting (m,2) zonotopes with designs and quadrature rules. Parameters ---------- vertices : ndarray M-by-2 matrix that contains the vertices that define the zonotope design : ndarray, optional N-by-2 matrix that contains a design-of-experiments on the zonotope. The plot will contain the Delaunay triangulation of the points in `design` and `vertices`. (default None) y : ndarray, optional K-by-2 matrix that contains points to be plotted inside the zonotope. If `y` is given, then `f` must be given, too. (default None) f: ndarray, optional K-by-1 matrix that contains a color value for the associated points in `y`. This is useful for plotting function values or quadrature rules with the zonotope. If `f` is given, then `y` must be given, too. (default None) out_label : str, optional a label for the quantity of interest (default None) opts : dict, optional a dictionary with some plot options (default None) Notes ----- This function makes use of the scipy.spatial routines for plotting the zonotopes. """ if opts == None: opts = plot_opts() # set labels for plots if out_label is None: out_label = 'Output' if vertices.shape[1] != 2: raise Exception('Zonotope vertices should be 2d.') if design is not None: if design.shape[1] != 2: raise Exception('Zonotope design should be 2d.') if y is not None: if y.shape[1] != 2: raise Exception('Zonotope design should be 2d.') if (y is not None and f is None) or (y is None and f is not None): raise Exception('You need both y and f to plot.') if y is not None and f is not None: if y.shape[0] != f.shape[0]: raise Exception('Lengths of y and f are not the same.') # get the xlim and ylim xmin, xmax = np.amin(vertices), np.amax(vertices) # make the Polygon patch for the zonotope ch = ConvexHull(vertices) # make the Delaunay triangulation if design is not None: points = np.vstack((design, vertices)) dtri = Delaunay(points) fig = plt.figure(figsize=(7,7)) ax = fig.add_subplot(111) fig0 = convex_hull_plot_2d(ch, ax=ax) for l in fig0.axes[0].get_children(): if type(l) is Line2D: l.set_linewidth(3) if design is not None: fig1 = delaunay_plot_2d(dtri, ax=ax) for l in fig1.axes[0].get_children(): if type(l) is Line2D: l.set_color('0.75') if y is not None: plt.scatter(y[:,0], y[:,1], c=f, s=100.0, vmin=np.min(f), vmax=np.max(f)) plt.axes().set_aspect('equal') plt.title(out_label) plt.colorbar() plt.axis([1.1*xmin,1.1*xmax,1.1*xmin,1.1*xmax]) plt.xlabel('Active variable 1') plt.ylabel('Active variable 2') show_plot(plt) if opts['savefigs']: figname = 'figs/zonotope_2d_' + out_label + opts['figtype'] plt.savefig(figname, dpi=300, bbox_inches='tight', pad_inches=0.0)