我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.colorbar()。
def plot_pts(points, values, colorbar=True, subplot_loc=None, mytitle=None, show_axis='on', vmin=None, vmax=None, xlim=(0,1), ylim=(0,1)): if subplot_loc is not None: plt.subplot(subplot_loc) pp = plt.scatter(points[:,0], points[:,1], c=values.get_local(), marker=",", s=20, vmin=vmin, vmax=vmax) plt.axis(show_axis) if colorbar: plt.colorbar(pp, fraction=.1, pad=0.2) else: plt.gca().set_aspect('equal') if mytitle is not None: plt.title(mytitle, fontsize=20) if xlim is not None: plt.xlim(xlim) if ylim is not None: plt.ylim(ylim) return pp
def plot_interpolation(orderx,ordery): s = PseudoSpectralDiscretization2D(orderx,XMIN,XMAX, ordery,YMIN,YMAX) Xc,Yc = s.get_x2d() x = np.linspace(XMIN,XMAX,100) y = np.linspace(YMIN,YMAX,100) Xf,Yf = np.meshgrid(x,y,indexing='ij') f_coarse = f(Xc,Yc) f_interpolator = s.to_continuum(f_coarse) f_num = f_interpolator(Xf,Yf) plt.pcolor(Xf,Yf,f_num) cb = plt.colorbar() cb.set_label('interpolated function',fontsize=16) plt.xlabel('x') plt.ylabel('y') for postfix in ['.png','.pdf']: name = 'orthopoly_interpolated_function'+postfix if USE_FIGS_DIR: name = 'figs/' + name plt.savefig(name, bbox_inches='tight') plt.clf()
def legend(self, mappable): fig = plt.gcf() posn = self.axes.get_position() extent = self.axes.get_extent() aspect = (extent[1] - extent[0]) / (extent[3] - extent[2]) self.cb_depth = 0.02 self.cb_sep = 0.01 if aspect < 1.2: self.cbar_ax = fig.add_axes([posn.x1 + self.cb_sep, posn.y0, self.cb_depth, posn.height]) plt.colorbar(mappable, ax=self.axes, orientation='vertical', cax=self.cbar_ax) else: self.cbar_ax = fig.add_axes([posn.x0, posn.y0 - 6*self.cb_sep, posn.width, 2*self.cb_depth]) plt.colorbar(mappable, ax=self.axes, orientation='horizontal', cax=self.cbar_ax) fig.canvas.mpl_connect('resize_event', self.resize_colourbar) self.resize_colourbar(None)
def plot_spectra(results): plt.figure(figsize=(10, 4)) plt.imshow( np.concatenate( [np.flipud(results['x'].T), np.flipud(results['xh'].T), np.flipud(results['x_conv'].T)], 0), aspect='auto', cmap='jet', ) plt.colorbar() plt.title('Upper: Real input; Mid: Reconstrution; Lower: Conversion to target.') plt.savefig( os.path.join( args.logdir, '{}.png'.format( os.path.split(str(results['f'], 'utf-8'))[-1] ) ) )
def plot_confusion_matrix(cm, target_names, title='Confusion matrix', cmap=plt.cm.Greys, block=True): # Colormaps: jet, Greys cm_normalized = cm.astype(np.float32) / cm.sum(axis=1)[:, np.newaxis] plt.imshow(cm_normalized, interpolation='nearest', cmap=cmap) # Show confidences for i, cas in enumerate(cm): for j, c in enumerate(cas): if c > 0: plt.text(j-0.1, i+0.2, c, fontsize=16, fontweight='bold', color='#b70000') f = plt.figure(1) f.clf() plt.title(title) plt.colorbar() tick_marks = np.arange(len(target_names)) plt.xticks(tick_marks, target_names, rotation=45) plt.yticks(tick_marks, target_names) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.show(block=block)
def plot_confusion_matrix(cm, clf_target_names, title='Confusion matrix', cmap=plt.cm.jet): target_names = map(lambda key: key.replace('_','-'), clf_target_names) for idx in range(len(cm)): cm[idx,:] = (cm[idx,:] * 100.0 / np.sum(cm[idx,:])).astype(np.int) plt.imshow(cm, interpolation='nearest', cmap=cmap) # plt.matshow(cm) plt.title(title) plt.colorbar() tick_marks = np.arange(len(clf_target_names)) plt.xticks(tick_marks, target_names, rotation=45) plt.yticks(tick_marks, target_names) # plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label')
def plot_confusion_matrix(cm, target_names, title='Confusion matrix', cmap=plt.cm.Greys): # Colormaps: jet, Greys cm_normalized = cm.astype(np.float32) / cm.sum(axis=1)[:, np.newaxis] plt.imshow(cm_normalized, interpolation='nearest', cmap=cmap) # Show confidences for i, cas in enumerate(cm): for j, c in enumerate(cas): if c > 0: plt.text(j-0.1, i+0.2, c, fontsize=16, fontweight='bold', color='#b70000') plt.title(title) plt.colorbar() tick_marks = np.arange(len(target_names)) plt.xticks(tick_marks, target_names, rotation=45) plt.yticks(tick_marks, target_names) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.show(block=True)
def plot_confusion_matrix(cm, col, title, cmap=plt.cm.viridis): plt.imshow(cm, interpolation='nearest', cmap=cmap) for i in range(cm.shape[0]): plt.annotate("%.2f" %cm[i][i],xy=(i,i), horizontalalignment='center', verticalalignment='center') plt.title(title,fontsize=18) plt.colorbar(fraction=0.046, pad=0.04) tick_marks = np.arange(len(col.unique())) plt.xticks(tick_marks, sorted(col.unique()),rotation=90) plt.yticks(tick_marks, sorted(col.unique())) plt.tight_layout() plt.ylabel('True label',fontsize=18) plt.xlabel('Predicted label',fontsize=18) #using flavor network to project recipes from ingredient matrix to flavor matrix
def plot_training_parameters(self): fr = open("training_param.csv", "r") fr.readline() lines = fr.readlines() fr.close() n = 100 nu = np.empty(n, dtype=np.float64) gamma = np.empty(n, dtype=np.float64) diff = np.empty([n, n], dtype=np.float64) for row in range(len(lines)): m = lines[row].strip().split(",") i = row / n j = row % n nu[i] = Decimal(m[0]) gamma[j] = Decimal(m[1]) diff[i][j] = Decimal(m[2]) plt.pcolor(gamma, nu, diff, cmap="coolwarm") plt.title("The Difference of Guassian Classifier with Different nu, gamma") plt.xlabel("gamma") plt.ylabel("nu") plt.xscale("log") plt.yscale("log") plt.colorbar() plt.show()
def Plot_ChargesDensity(XYZ, sig0, sig1, R, E0, ax): xr, yr, zr = np.unique(XYZ[:, 0]), np.unique(XYZ[:, 1]), np.unique(XYZ[:, 2]) xcirc = xr[np.abs(xr) <= R] Et, Ep, Es = get_ElectricField(XYZ, sig0, sig1, R, E0) rho = get_ChargesDensity(XYZ, sig0, sig1, R, Et, Ep) ax.set_xlim([xr.min(), xr.max()]) ax.set_ylim([yr.min(), yr.max()]) ax.set_aspect('equal') Cplot = ax.pcolor(xr, yr, rho.reshape(xr.size, yr.size)) cb1 = plt.colorbar(Cplot, ax=ax) cb1.set_label(label= 'Charge Density ($C/m^2$)', size=ftsize_label) #weight='bold') cb1.ax.tick_params(labelsize=ftsize_axis) ax.plot(xcirc, np.sqrt(R**2-xcirc**2), '--k', xcirc, -np.sqrt(R**2-xcirc**2), '--k') ax.set_ylabel('Y coordinate ($m$)', fontsize=ftsize_label) ax.set_xlabel('X coordinate ($m$)', fontsize=ftsize_label) ax.tick_params(labelsize=ftsize_axis) ax.set_title('Charges Density', fontsize=ftsize_title) return ax
def showHeightMap(x,y,z,zi): ''' show height map in maptplotlib ''' zi=zi.transpose() plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower', extent=[ y.min(), y.max(),x.min(), x.max()]) plt.colorbar() CS = plt.contour(zi,15,linewidths=0.5,colors='k', extent=[ y.min(), y.max(),x.min(), x.max()]) CS = plt.contourf(zi,15,cmap=plt.cm.rainbow, extent=[ y.min(), y.max(),x.min(), x.max()]) z=z.transpose() plt.scatter(y, x, c=z) # achsen umkehren #plt.gca().invert_xaxis() #plt.gca().invert_yaxis() plt.show() return
def fft_convolve(X,Y, inv = 0): XF = np.fft.rfft2(X) YF = np.fft.rfft2(Y) # YF0 = np.copy(YF) # YF.imag = 0 # XF.imag = 0 if inv == 1: # plt.imshow(np.real(YF)); plt.colorbar(); plt.show() YF = np.conj(YF) SF = XF*YF S = np.fft.irfft2(SF) n1,n2 = np.shape(S) S = np.roll(S,-n1/2+1,axis = 0) S = np.roll(S,-n2/2+1,axis = 1) return np.real(S)
def epsilon_enhance(img, g, rho, mu, tau): alpha0 = ridgelet(img) alpha = np.abs(alpha0) lvl,na1,na2 = np.shape(alpha) n1,n2 = np.shape(img) sigma = MAD(img) level = mk_thresh(n1,n2)*sigma alpha_enhanced = np.copy(alpha)*0 for i in range(lvl-1): alpha_enhanced[i, np.where(alpha[i,:,:]<mu)] = (mu/(alpha[i,np.where(alpha[i,:,:].astype(float)<mu)]))**g plt.imshow(np.log10(alpha_enhanced[i,:,:])); plt.title('mu');plt.colorbar(); plt.show() alpha_enhanced[i, np.where(alpha[i,:,:]<2*tau*level[i])] = ((alpha[i, np.where(alpha[i,:,:]<2*tau*level[i])].astype(float)-tau*level[i])/(tau*level[i]))*(mu/(tau*level[i]))**g +(2*tau*level[i]-alpha[i, np.where(alpha[i,:,:]<2*tau*level[i])].astype(float))/(tau*level[i]) plt.imshow(np.log10(alpha_enhanced[i,:,:])); plt.title('2sigma');plt.colorbar(); plt.show() alpha_enhanced[i, np.where(alpha[i,:,:]<tau*level[i])] = 1. plt.imshow(np.log10(alpha_enhanced[i,:,:])); plt.title('1'); plt.colorbar(); plt.show() alpha_enhanced[i, np.where(alpha[i,:,:]>=mu)] = (mu/alpha[i,np.where(alpha[i,:,:]>=mu)].astype(float))**rho plt.imshow(np.log10(alpha_enhanced[i,:,:]));plt.title('final'); plt.colorbar(); plt.show() alpha_enhanced[-1,:,:] = 1 return alpha0*alpha_enhanced
def pretty_spectrogram(spectrogram): """ Gent Master thesis spectrogram plot function """ spectrogram = np.transpose(spectrogram, (2,1,0)) ax = plt.gca() ax.set_yticks(range(0,6)) ax.set_yticklabels([ 'delta', 'theta', 'alpha', 'beta', 'low-gamma', 'high-gamma']) for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(20) ax.set_xticks(range(0,10)) ax.set_xticklabels(range(0,10)) plt.imshow(spectrogram[0, :, :], aspect='auto', origin='lower', interpolation='none') cbar = plt.colorbar() cbar.ax.tick_params(labelsize=20) plt.xlabel('Time, Epoch', fontsize=20) plt.show()
def phase_diagram_mesh(points, values, title="Phase diagram", xlabel="Pulse Duration (s)", ylabel="Pulse Amplitude (V)", shading="flat", voronoi=False, **kwargs): # fig = plt.figure() if voronoi: from scipy.spatial import Voronoi, voronoi_plot_2d points[:,0] *= 1e9 vor = Voronoi(points) cmap = mpl.cm.get_cmap('RdGy') # colorize for pr, v in zip(vor.point_region, values): region = vor.regions[pr] if not -1 in region: polygon = [vor.vertices[i] for i in region] plt.fill(*zip(*polygon), color=cmap(v)) else: mesh = scaled_Delaunay(points) xs = mesh.points[:,0] ys = mesh.points[:,1] plt.tripcolor(xs,ys,mesh.simplices.copy(),values, cmap="RdGy",shading=shading,**kwargs) plt.xlim(min(xs),max(xs)) plt.ylim(min(ys),max(ys)) plt.title(title, size=18) plt.xlabel(xlabel, size=16) plt.ylabel(ylabel, size=16) cb = plt.colorbar() cb.set_label("Probability",size=16) return mesh
def update(self, conf_mat, classes, normalize=False): """This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ plt.imshow(conf_mat, interpolation='nearest', cmap=self.cmap) plt.title(self.title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: conf_mat = conf_mat.astype('float') / conf_mat.sum(axis=1)[:, np.newaxis] thresh = conf_mat.max() / 2. for i, j in itertools.product(range(conf_mat.shape[0]), range(conf_mat.shape[1])): plt.text(j, i, conf_mat[i, j], horizontalalignment="center", color="white" if conf_mat[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.draw()
def plot_normalized_confusion_matrix_at_depth(self): """ Returns a normalized confusion matrix. :returns: normalized confusion matrix :rtype: matplotlib figure """ cm = metrics.confusion_matrix(self.predictions['label'], self.y_pred) np.set_printoptions(precision = 2) fig = plt.figure() cm_normalized = cm.astype('float') / cm.sum(axis = 1)[:, np.newaxis] plt.imshow(cm_normalized, interpolation = 'nearest', cmap = plt.cm.Blues) plt.title("Normalized Confusion Matrix") plt.colorbar() tick_marks = np.arange(len(self.labels)) plt.xticks(tick_marks, self.labels, rotation = 45) plt.yticks(tick_marks, self.labels) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') return(fig)
def plotImage(dta, saveFigName): plt.clf() dx, dy = 1, 1 # generate 2 2d grids for the x & y bounds with np.errstate(invalid='ignore'): y, x = np.mgrid[ slice(0, len(dta) , dx), slice(0, len(dta[0]), dy) ] z = dta z_min, z_max = -np.abs(z).max(), np.abs(z).max() #try: c = plt.pcolormesh(x, y, z, cmap='hsv', vmin=z_min, vmax=z_max) #except ??? as err: # data not regular? # c = plt.pcolor(x, y, z, cmap='hsv', vmin=z_min, vmax=z_max) d = plt.colorbar(c, orientation='vertical') lx = plt.xlabel("index") ly = plt.ylabel("season length") plt.savefig(str(saveFigName))
def sample(config, vae): x_sample = mnist.test.next_batch(100)[0] x_reconstruct = vae.reconstruct(x_sample) plt.figure(figsize=(8, 12)) for i in range(5): plt.subplot(5, 2, 2*i + 1) plt.imshow(x_sample[i].reshape(28, 28), vmin=0, vmax=1) plt.title("Test input") plt.colorbar() plt.subplot(5, 2, 2*i + 2) plt.imshow(x_reconstruct[i].reshape(28, 28), vmin=0, vmax=1) plt.title("Reconstruction") plt.colorbar() plt.tight_layout() img = "samples/reconstruction.png" plt.savefig(img) hc.io.sample(config, [{"label": "Reconstruction", "image": img}])
def saturation_index_countour(lab, elem1, elem2, Ks, labels=False): plt.figure() plt.title('Saturation index %s%s' % (elem1, elem2)) resoluion = 100 n = math.ceil(lab.time.size / resoluion) plt.xlabel('Time') z = np.log10((lab.species[elem1]['concentration'][:, ::n] + 1e-8) * ( lab.species[elem2]['concentration'][:, ::n] + 1e-8) / lab.constants[Ks]) lim = np.max(abs(z)) lim = np.linspace(-lim - 0.1, +lim + 0.1, 51) X, Y = np.meshgrid(lab.time[::n], -lab.x) plt.xlabel('Time') CS = plt.contourf(X, Y, z, 20, cmap=ListedColormap(sns.color_palette( "RdBu_r", 101)), origin='lower', levels=lim, extend='both') if labels: plt.clabel(CS, inline=1, fontsize=10, colors='w') # cbar = plt.colorbar(CS) if labels: plt.clabel(CS, inline=1, fontsize=10, colors='w') cbar = plt.colorbar(CS) plt.ylabel('Depth') ax = plt.gca() ax.ticklabel_format(useOffset=False) cbar.ax.set_ylabel('Saturation index %s%s' % (elem1, elem2)) return ax
def contour_plot_of_rates(lab, r, labels=False, last_year=False): plt.figure() plt.title('{}'.format(r)) resoluion = 100 n = math.ceil(lab.time.size / resoluion) if last_year: k = n - int(1 / lab.dt) else: k = 1 z = lab.estimated_rates[r][:, k - 1:-1:n] # lim = np.max(np.abs(z)) # lim = np.linspace(-lim - 0.1, +lim + 0.1, 51) X, Y = np.meshgrid(lab.time[k::n], -lab.x) plt.xlabel('Time') CS = plt.contourf(X, Y, z, 20, cmap=ListedColormap( sns.color_palette("Blues", 51))) if labels: plt.clabel(CS, inline=1, fontsize=10, colors='w') cbar = plt.colorbar(CS) plt.ylabel('Depth') ax = plt.gca() ax.ticklabel_format(useOffset=False) cbar.ax.set_ylabel('Rate %s [M/V/T]' % r) return ax
def contour_plot_of_delta(lab, element, labels=False, last_year=False): plt.figure() plt.title('Rate of %s consumption/production' % element) resoluion = 100 n = math.ceil(lab.time.size / resoluion) if last_year: k = n - int(1 / lab.dt) else: k = 1 z = lab.species[element]['rates'][:, k - 1:-1:n] lim = np.max(np.abs(z)) lim = np.linspace(-lim - 0.1, +lim + 0.1, 51) X, Y = np.meshgrid(lab.time[k:-1:n], -lab.x) plt.xlabel('Time') CS = plt.contourf(X, Y, z, 20, cmap=ListedColormap(sns.color_palette( "RdBu_r", 101)), origin='lower', levels=lim, extend='both') if labels: plt.clabel(CS, inline=1, fontsize=10, colors='w') cbar = plt.colorbar(CS) plt.ylabel('Depth') ax = plt.gca() ax.ticklabel_format(useOffset=False) cbar.ax.set_ylabel('Rate of %s change $[\Delta/T]$' % element) return ax
def plot(self, ax=None, clim=[None, None], pcolorOpts=None): """ plot the electrical conductivity and relative permeability :param matplotlib.axes ax: axis :param list clim: list of numpy arrays: colorbar limits :param dict pcolorOpts: dictionary of pcolor options """ if ax is None: fig, ax = plt.subplots(1, 2, figsize=(12, 4)) if not isinstance(pcolorOpts, list): pcolorOpts = [pcolorOpts]*2 self.plot_sigma(ax=ax[0], clim=clim[0], pcolorOpts=pcolorOpts[0]) self.plot_mur(ax=ax[1], clim=clim[1], pcolorOpts=pcolorOpts[1]) plt.tight_layout() return ax
def _2Dplot(X, xvec, yvec, title='', xlabel='', ylabel='', cmap='viridis', cblabel='', maxplot=10, interp=(1, 1), **kwargs): """Simple 2D plot""" def _sub2Dplot(X): if (interp[0], interp[1]) != (1, 1): X, xV, yV = mapinterpolation(X, x=xvec, y=yvec, interpx=interp[1], interpy=interp[0]) else: xV, yV = xvec, yvec im = plt.imshow(X, cmap=cmap, aspect='auto', extent=[xV[ 0], xV[-1], yV[-1], yV[0]], **kwargs) ax = plt.gca() ax.set_xlabel(xlabel), ax.set_ylabel(ylabel) ax.set_title(title) ax.invert_yaxis() cb = plt.colorbar(im) cb.set_label(cblabel) return ax return _sub(X, _sub2Dplot, maxplot=maxplot)
def show_image(im: Image, fig=None, title: str = '', pol=0, chan=0, cm='rainbow'): """ Show an Image with coordinates using matplotlib :param im: :param fig: :param title: :return: """ import matplotlib.pyplot as plt assert isinstance(im, Image) if not fig: fig = plt.figure() plt.clf() fig.add_subplot(111, projection=im.wcs.sub(['longitude', 'latitude'])) if len(im.data.shape) == 4: plt.imshow(numpy.real(im.data[chan, pol, :, :]), origin='lower', cmap=cm) elif len(im.data.shape) == 2: plt.imshow(numpy.real(im.data[:, :]), origin='lower', cmap=cm) plt.xlabel('RA---SIN') plt.ylabel('DEC--SIN') plt.title(title) plt.colorbar() return fig
def __init__(self, hic_matrix, regions=None, colormap='RdBu', norm="log", vmin=None, vmax=None, show_colorbar=True, blend_masked=False): if regions is None: for i in range(hic_matrix.shape[0]): regions.append(GenomicRegion(chromosome='', start=i, end=i)) self.regions = regions self.hic_matrix = hic_matrix self.colormap = copy.copy(mpl.cm.get_cmap(colormap)) if blend_masked: self.colormap.set_bad(self.colormap(0)) self._vmin = vmin self._vmax = vmax self.norm = prepare_normalization(norm=norm, vmin=vmin, vmax=vmax) self.colorbar = None self.slider = None self.show_colorbar = show_colorbar
def plot_confusion_matrix(cm, names=None, title='Confusion Matrix', cmap=plt.cm.Blues): plt.figure(4) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() # Add labels to confusion matrix: if names is None: names = range(cm.shape[0]) tick_marks = np.arange(len(names)) plt.xticks(tick_marks, names, rotation=45) plt.yticks(tick_marks, names) plt.tight_layout() plt.ylabel('Correct label') plt.xlabel('Predicted label') plt.show() # Generate confusion matrix for Jaffe # results = list of tuples of (correct label, predicted label) # e.g. [ ('HA', 3) ] # categories = list of category names # Returns confusion matrix; rows are correct labels and columns are predictions
def test_face(Img, CAE, n_input): batch_x_test = Img[200:300,:] batch_x_test= np.reshape(batch_x_test,[100,n_input[0],n_input[1],1]) CAE.restore() x_re = CAE.reconstruct(batch_x_test) plt.figure(figsize=(8,12)) for i in range(5): plt.subplot(5,2,2*i+1) plt.imshow(batch_x_test[i,:,:,0], vmin=0, vmax=255, cmap="gray") # plt.title("Test input") plt.colorbar() plt.subplot(5, 2, 2*i + 2) plt.imshow(x_re[i,:,:,0], vmin=0, vmax=255, cmap="gray") plt.title("Reconstruction") plt.colorbar() plt.tight_layout() plt.show() return
def show(w, w_title): """ Show a weight matrix. :param w: the weight matrix. :param w_title: the title of the weight matrix :return: None. """ # show w_z matrix of update gate. axes_w = plt.gca() plt.imshow(w) plt.colorbar() # plt.colorbar(orientation="horizontal") plt.xlabel("$w_{1}$") plt.ylabel("$w_{2}$") axes_w.set_xticks([]) axes_w.set_yticks([]) matrix_size = "$:\ %d \\times\ %d$" % (len(w[0]), len(w)) w_title += matrix_size plt.title(w_title) # show the matrix. plt.show()
def heatmap(data,ax,xlabel=None,ylabel=None,xticklabels=None,yticklabels=None,title=None,fontsize=12): ''' ??matplotlib.pyplot.pcolor????? ?????(pc,ax)???pc????matplotlib.pyplot.colorbar??????mappable? ''' pc=ax.pcolor(data,cmap=plt.cm.Blues) if xlabel is not None: ax.set_xlabel(xlabel,fontsize=fontsize) if ylabel is not None: ax.set_ylabel(ylabel,fontsize=fontsize) ax.set_xticks(np.arange(data.shape[1])+0.5,minor=False) if xticklabels is not None: ax.set_xticklabels(xticklabels,minor=False,fontsize=fontsize) ax.set_yticks(np.arange(data.shape[0])+0.5,minor=False) if yticklabels is not None: ax.set_yticklabels(yticklabels,minor=False,fontsize=fontsize) if title is not None: ax.set_title(title,fontsize=fontsize) return pc,ax #????X?Y????
def test_discrete_phantom_uniform(): """The uniform discrete phantom is the same after rotating 90 degrees.""" d0 = discrete_phantom(p, 100, ratio=10, prop='mass_atten') p.rotate(theta=np.pi/2, point=Point([0.5, 0.5])) d1 = np.rot90(discrete_phantom(p, 100, ratio=10, prop='mass_atten')) # plot rotated phantom plot_phantom(p) # plot the error plt.figure() plt.imshow(d1-d0, interpolation=None) plt.colorbar() # plt.show(block=True) # assert_allclose(d0, d1)
def plot_pauli_transfer_matrix(ptransfermatrix, ax, labels, title): """ Visualize the Pauli Transfer Matrix of a process. :param numpy.ndarray ptransfermatrix: The Pauli Transfer Matrix :param ax: The matplotlib axes. :param labels: The labels for the operator basis states. :param title: The title for the plot :return: The modified axis object. :rtype: AxesSubplot """ im = ax.imshow(ptransfermatrix, interpolation="nearest", cmap=rigetti_3_color_cm, vmin=-1, vmax=1) dim = len(labels) plt.colorbar(im, ax=ax) ax.set_xticks(range(dim)) ax.set_xlabel("Input Pauli Operator", fontsize=20) ax.set_yticks(range(dim)) ax.set_ylabel("Output Pauli Operator", fontsize=20) ax.set_title(title, fontsize=25) ax.set_xticklabels(labels, rotation=45) ax.set_yticklabels(labels) ax.grid(False) return ax
def SurfacePlot(self, grib_object, file_name): """Generate a 3D surface colored plot grib_object: an object containing raw data to be visualized file_name: a string representing the name of generated picture """ data = grib_object.values lat,lon = grib_object.latlons() fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = lon y = lat z = data surf = ax.plot_surface(x, y, z, cmap=plt.cm.coolwarm, rstride=15, cstride=15, linewidth=0, antialiased=False) # Set Lables self.setPlotLabels(ax, grib_object) self.setTitle(ax, grib_object) fig.colorbar(surf, shrink=0.5, aspect=5) plt.savefig(file_name)
def display_confusion_matrix(test_data, test_labels, save=False): """ Plot a matrix representing the choices made by the network on a testing batch. X axis are the predicted values, Y axis are the expected values. If the flag save is set to True, the output will be saved in a .png image. """ expected = test_labels predicted = mnist.predict(test_data) cm = confusion_matrix(expected, predicted) plt.matshow(cm) plt.title('Confusion matrix') plt.colorbar() plt.ylabel('Expected label') plt.xlabel('Predicted label') plt.show() if save is True: plt.savefig("../results/mnist/confusion_matrix.png")
def display_saliency_overlay(image, saliency_map, shape=(28, 28)): """ Plot overlay saliency map over image. Args: image: numpy array (1d vector) for single image saliency_map: numpy array (1d vector) for image shape: the dimensions of the image. defaults to mnist. """ if len(image.shape) == 3 or len(saliency_map.shape) == 3: image = image[0] saliency_map = saliency_map[0] elif len(image.shape) == 1 or len(saliency_map.shape) == 1: image = np.reshape(image, shape) saliency_map = np.reshape(saliency_map, shape) fig = plt.figure() fig.add_subplot(1, 2, 1) plt.imshow(image, cmap='gray') fig.add_subplot(1, 2, 2) plt.imshow(image, cmap='binary') plt.imshow(abs(saliency_map), cmap='hot_r', alpha=0.7) plt.colorbar() plt.show(False)
def create_fig(self): fig = plt.figure(figsize=(16,6)) ax1 = fig.add_subplot(1, 1, 1) ax1.cla() ax1.hold(True) self.time_str = 'time = %-6.2f' ax1.set_title( '' ) ax1.set_xlabel('X') ax1.set_ylabel('Y') self.ax1 = ax1 plt.ion() self.im=ax1.imshow( self.z2d, vmin=self.cax[0],vmax=self.cax[1], cmap=plt.get_cmap('jet'),origin='lower', interpolation='nearest') cb = plt.colorbar(self.im) fig.show() fig.canvas.draw() self.fig = fig
def visualizeCrossValidation(results): # Visualize the cross-validation results x_scatter = [math.log10(x[0]) for x in results] y_scatter = [math.log10(x[1]) for x in results] # plot training accuracy marker_size = 100 colors = [results[x][0] for x in results] plt.subplot(2, 1, 1) plt.scatter(x_scatter, y_scatter, marker_size, c=colors) plt.colorbar() plt.xlabel('log learning rate') plt.ylabel('log regularization strength') plt.title('CIFAR-10 training accuracy') # plot validation accuracy colors = [results[x][1] for x in results] # default size of markers is 20 plt.subplot(2, 1, 2) plt.scatter(x_scatter, y_scatter, marker_size, c=colors) plt.colorbar() plt.xlabel('log learning rate') plt.ylabel('log regularization strength') plt.title('CIFAR-10 validation accuracy') plt.show()
def plotD(initD, latestD, workDir): def p(D, fname): plt.clf() lim = max(np.abs(np.min(D)), np.abs(np.max(D))) clim = (-lim, lim) plt.imshow(D, cmap='bwr', interpolation='nearest', clim=clim) plt.colorbar() plt.savefig(os.path.join(workDir, fname)) p(initD, 'initD.png') p(latestD, 'latestD.png') latestDs = latestD**6 latestDs = latestDs/np.sum(latestDs, axis=1)[:,None] I = np.argsort(latestDs.dot(np.arange(latestDs.shape[1]))) latestDs = latestD[I] initDs = initD[I] p(initDs, 'initD_sorted.png') p(latestDs, 'latestD_sorted.png') # Dcombined = np.concatenate((initDs, np.zeros((initD.shape[0], 10)), latestDs), axis=1) # p(Dcombined, 'Dcombined.png')
def plot_test_function(orderx,ordery): s = PseudoSpectralDiscretization2D(orderx,XMIN,XMAX, ordery,YMIN,YMAX) X,Y = s.get_x2d() f_ana = f(X,Y) plt.pcolor(X,Y,f_ana) plt.xlabel('x',fontsize=16) plt.ylabel('y',fontsize=16) plt.xlim(XMIN,XMAX) plt.ylim(YMIN,YMAX) cb = plt.colorbar() cb.set_label(label=r'$\cos(x)\sin(2 y)$',fontsize=16) for postfix in ['.png','.pdf']: name = 'test_function'+postfix if USE_FIGS_DIR: name = 'figs/' + name plt.savefig(name, bbox_inches='tight') plt.clf()
def show_heatmap(x, y, attention): #print attention[:len(y),:len(x)] #print attention[:len(y),:len(x)].shape #data = np.transpose(attention[:len(y),:len(x)]) data = attention[:len(y),:len(x)] x, y = y, x #ax = plt.axes(aspect=0.4) ax = plt.axes() heatmap = plt.pcolor(data, cmap=plt.cm.Blues) xticks = np.arange(len(y)) + 0.5 xlabels = y yticks = np.arange(len(x)) + 0.5 ylabels = x plt.xticks(xticks, xlabels, rotation='vertical') ax.set_yticks(yticks) ax.set_yticklabels(ylabels) # make it look less like a scatter plot and more like a colored table ax.tick_params(axis='both', length=0) ax.invert_yaxis() ax.xaxis.tick_top() plt.colorbar(heatmap) plt.show() #plt.savefig('./attention-out.pdf')
def start_simulation(self): """Starts the simulation with visualization.""" self.show_setup(halt=False) main_plot = self.axes.imshow(self.field_as_matrix(), extent=(0, max(self.field.x.vector) / self._x_axis_factor, max(self.field.y.vector) / self._y_axis_factor, 0), cmap='viridis') main_plot.set_clim(-self.scale, self.scale) color_bar = pp.colorbar(main_plot) color_bar.set_label(self.observed_component, rotation=270) sim_process = mp.Process(target=self._sim_function, args=(self._plot_queue,)) sim_process.start() # wait for simulation initialization while self._plot_queue.empty(): pl.pause(0.1) finished = False while not finished: # wait for new simulation result while self._plot_queue.empty(): pl.pause(0.01) message = self._plot_queue.get() # simulation function returns field object when simulation is complete to get output if isinstance(message, fld.Field): # update main process field components with simulation result self._update_components(message) finished = True else: time, data = message self.axes.title.set_text('{title} $t$ = {time:.{prec}f} {prefix}s' .format(title=self.plot_title, time=time/self._t_factor, prec=self.time_precision, prefix=self._t_prefix)) main_plot.set_data(self.field_as_matrix(data)) pl.pause(self.frame_delay) sim_process.join() pp.show()
def train(epoch): if epoch > 2: import pdb; pdb.set_trace() model.train() for batch_idx, (data, target) in enumerate(train_loader): # 1. Add requires_grad so Torch doesn't erase the gradient with its optimization pass data, target = Variable(data, requires_grad=True), Variable(target) optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() if batch_idx % args.log_interval == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.data[0])) # 2. Get the `.grad` attribute of the variable. # This is a Torch tensor, so to get the data as numpy format, we have to use `.grad.data.numpy()` adversarial_example = data.grad.data.numpy() print(adversarial_example.max()) if epoch > 2: # 3. Let's plot it, because we can! plt.clf() plt.subplot(121); plt.imshow(data.data.numpy()[0,0,...], cmap='gray_r') plt.subplot(122); plt.imshow(adversarial_example[0,0,...]); plt.colorbar() plt.show(block=False) plt.pause(0.01)
def plot(obj, colorbar=True, subplot_loc=None, mytitle=None, show_axis='off', vmin=None, vmax=None, logscale=False): if subplot_loc is not None: plt.subplot(subplot_loc) # plt.gca().set_aspect('equal') if isinstance(obj, dl.Function): pp = mplot_function(obj, vmin, vmax, logscale) elif isinstance(obj, dl.CellFunctionSizet): pp = mplot_cellfunction(obj) elif isinstance(obj, dl.CellFunctionDouble): pp = mplot_cellfunction(obj) elif isinstance(obj, dl.CellFunctionInt): pp = mplot_cellfunction(obj) elif isinstance(obj, dl.Mesh): if (obj.geometry().dim() != 2): raise AttributeError('Mesh must be 2D') pp = plt.triplot(mesh2triang(obj), color='#808080') colorbar = False else: raise AttributeError('Failed to plot %s'%type(obj)) plt.axis(show_axis) if colorbar: plt.colorbar(pp, fraction=.1, pad=0.2) else: plt.gca().set_aspect('equal') if mytitle is not None: plt.title(mytitle, fontsize=20) return pp
def multi1_plot(objs, titles, same_colorbar=True, show_axis='off', logscale=False): vmin = None vmax = None if same_colorbar: vmin = 1e30 vmax = -1e30 for f in objs: if isinstance(f, dl.Function): fmin = f.vector().min() fmax = f.vector().max() if fmin < vmin: vmin = fmin if fmax > vmax: vmax = fmax nobj = len(objs) if nobj == 1: plt.figure(figsize=(7.5,5)) subplot_loc = 110 elif nobj == 2: plt.figure(figsize=(15,5)) subplot_loc = 120 elif nobj == 3: plt.figure(figsize=(18,4)) subplot_loc = 130 else: raise AttributeError("Too many figures") for i in range(nobj): plot(objs[i], colorbar=True, subplot_loc=(subplot_loc+i+1), mytitle=titles[i], show_axis='off', vmin=vmin, vmax=vmax, logscale=logscale)
def show_solution(Vh, ic, state, same_colorbar=True, colorbar=True, mytitle=None, show_axis='off', logscale=False, times=[0, .4, 1., 2., 3., 4.]): state.store(ic, 0) assert len(times) % 3 == 0 nrows = len(times) / 3 subplot_loc = nrows*100 + 30 plt.figure(figsize=(18,4*nrows)) if mytitle is None: title_stamp = "Time {0}s" else: title_stamp = mytitle + " at time {0}s" vmin = None vmax = None if same_colorbar: vmin = 1e30 vmax = -1e30 for s in state.data: smax = s.max() smin = s.min() if smax > vmax: vmax = smax if smin < vmin: vmin = smin counter=1 myu = dl.Function(Vh) for i in times: try: state.retrieve(myu.vector(),i) except: print("Invalid time: ", i) plot(myu, subplot_loc=(subplot_loc+counter), mytitle=title_stamp.format(i), colorbar=colorbar, logscale=logscale, show_axis=show_axis, vmin=vmin, vmax=vmax) counter = counter+1
def animate(Vh, state, same_colorbar=True, colorbar=True, subplot_loc=None, mytitle=None, show_axis='off', logscale=False): fig = plt.figure() vmin = None vmax = None if same_colorbar: vmin = 1e30 vmax = -1e30 for s in state.data: smax = s.max() smin = s.min() if smax > vmax: vmax = smax if smin < vmin: vmin = smin def my_animate(i): time_stamp = "Time: {0:f} s" obj = dl.Function(Vh, state.data[i]) t = mytitle + time_stamp.format(state.times[i]) plt.clf() return plot(obj, colorbar=True, subplot_loc=None, mytitle=t, show_axis='off', vmin=vmin, vmax=vmax, logscale=False) return animation.FuncAnimation(fig, my_animate, np.arange(0, state.nsteps), blit=True)
def saveFinalPlots(self, errors_train, errors_test, sparsity_train, sparsity_test, errors_train_vector, errors_test_vector, epoch=0): #plot errors plt.figure(2, figsize=(10, 7)) plt.clf() plt.plot(np.arange(len(errors_train)), errors_train, label='train error') plt.plot(np.arange(len(errors_train)), errors_test, label='test error') plt.colors() plt.legend() plt.title('Reconstruction error convergence') plt.xlabel('t') plt.ylabel('Reconstruction error') plt.savefig('plots/Reconstruction_errors_'+str(epoch)+'.pdf') #plot sparsity, real and non-zero plt.figure(3, figsize=(10, 7)) plt.clf() plt.plot(np.arange(len(sparsity_train)), sparsity_train, label='train error') plt.plot(np.arange(len(sparsity_test)), sparsity_test, label='test error') plt.colors() plt.legend() plt.title('Objective function error convergence') plt.xlabel('t') plt.ylabel('E') plt.savefig('plots/Sparsity_'+str(epoch)+'.pdf') # plot reconstruction error output progression over time plt.figure(12, figsize=(10, 7)) plt.clf() image=plt.imshow(np.clip(np.asarray(errors_train_vector).T, 0, 1), interpolation='nearest', aspect='auto', origin='lower') plt.xlabel('t') plt.ylabel('Output units \n (Rank Ordered)') plt.colors() plt.colorbar(image, label='reconstruction error') plt.title('Progressive reconstruction input error convergence') plt.savefig('plots/Reconstruction_errors_vector_' + str(epoch) + '.pdf')
def main(): parser = argparse.ArgumentParser(description='') parser.add_argument('--transform') parser.add_argument('--out') args = parser.parse_args() infile1 = h5py.File(args.transform, 'r') resolutions = infile1['resolutions'][...] chroms = infile1['chromosomes'][...] data1 = load_data(infile1, chroms, resolutions) infile1.close() ''' #for now, don't plot this for resolution in data1.keys(): for chromo in chroms: N = data1[resolution][chromo][1].shape[0] full=numpy.empty((N,N)) #full=full/0 for i in range(100): temp1 = numpy.arange(N - i - 1) temp2 = numpy.arange(i+1, N) full[temp1, temp2] = data1[resolution][chromo][1][temp1, i] full[temp2, temp1] = full[temp1, temp2] x=0.8 plt.matshow(full,cmap='seismic',vmin=-x,vmax=x) plt.colorbar() plt.show() plt.savefig(args.out+'.res'+str(resolution)+'.chr'+chromo+'.pdf') '''