我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用matplotlib.pyplot.set_cmap()。
def plotImages(image_list, name_list, path, as_grey, toSave=False): """Plots the images given in image_list side by side.""" fig = plt.figure() imageCoordinate = 100 + 10*len(image_list) + 1 i = 0 for image in image_list: fig.add_subplot(imageCoordinate) plt.title(name_list[i]) plt.axis('off') plt.imshow(image) if as_grey: plt.set_cmap('gray') imageCoordinate += 1 i += 1 if toSave: plt.savefig("./plots/images/" + path + ".png",bbox_inches='tight') plt.show()
def plotImages(image_list, name_list, path, as_grey, toSave=False): """Plots the images given in image_list side by side.""" fig = plt.figure() imageCoordinate = 100 + 10*len(image_list) + 1 i = 0 for image in image_list: fig.add_subplot(imageCoordinate) plt.title(name_list[i]) plt.axis('off') plt.imshow(image) if as_grey: plt.set_cmap('gray') imageCoordinate += 1 i += 1 if toSave: plt.savefig(path + ".jpg",bbox_inches='tight') plt.show()
def _plot_single_map1(self, path, cmap, signo, dist_map, threshold, constrained, stretch, colorMap, suffix): import matplotlib.pyplot as plt if path != None: plt.ioff() grad = self.get_single_map(signo, cmap, dist_map, threshold, constrained, stretch) plt.imshow(grad, interpolation='none') plt.set_cmap(colorMap) cbar = plt.colorbar() cbar.set_ticks([]) if path != None: if suffix == None: fout = osp.join(path, '{0}_{1}.png'.format(self.label, signo)) else: fout = osp.join(path, '{0}_{1}_{2}.png'.format(self.label, signo, suffix)) try: plt.savefig(fout) except IOError: raise IOError('in classifiers.output, no such file or directory: {0}'.format(path)) else: if suffix == None: plt.title('{0} - EM{1}'.format(self.label, signo)) else: plt.title('{0} - EM{1} - {2}'.format(self.label, signo, suffix)) plt.show() plt.close()
def visualiseLearnedFeatures(self): """ Visualise the features learned by the autoencoder """ import matplotlib.pyplot as plt extent = np.sqrt(self._architecture[0]) # size of input vector is stored in self._architecture # number of rows and columns to plot (number of hidden units also stored in self._architecture) plotDims = np.rint(np.sqrt(self._architecture[1])) plt.ion() fig = plt.figure() plt.set_cmap("gnuplot") plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=-0.6, hspace=0.1) learnedFeatures = self.getLearnedFeatures() for i in range(self._architecture[1]): image = np.reshape(learnedFeatures[i,:], (extent, extent), order="F") * 1000 ax = fig.add_subplot(plotDims, plotDims, i) plt.axis("off") ax.imshow(image, interpolation="nearest") plt.show() raw_input("Program paused. Press enter to continue.")
def visualiseLearnedFeatures(self): """ Visualise the features learned by the autoencoder """ import matplotlib.pyplot as plt extent = np.sqrt(self._architecture[0]) # size of input vector is stored in self._architecture # number of rows and columns to plot (number of hidden units also stored in self._architecture) plotDims = np.rint(np.sqrt(self._architecture[1])) plt.ion() fig = plt.figure() plt.set_cmap("gnuplot") plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=-0.6, hspace=0.1) learnedFeatures = self.getLearnedFeatures() for i in range(self._architecture[1]): image = np.reshape(learnedFeatures[i,:], (extent, extent), order="F") * 1000 ax = fig.add_subplot(plotDims, plotDims, i) plt.axis("off") ax.imshow(image, interpolation="nearest") plt.show() input("Program paused. Press enter to continue.")
def showimage(img): if img.ndim == 3: img = img[:, :, ::-1] plt.set_cmap('jet') plt.imshow(img,vmin=0, vmax=0.2) # Display network activations
def plot_defect_classifications(bmp, list_of_classified_defects, unclassified_defect_region, td_classify, defect_free_region): plt.rcParams['figure.figsize'] = (10.0, 10.0); plt.set_cmap('gray'); fig = plt.figure(); ax = fig.add_subplot(111); fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None); # Plot the labeled defect regions on top of the temperature field bmp[defect_free_region==1.] = 0.5*bmp[defect_free_region==1.] # Defect-free region txt_out = [] for defect in list_of_classified_defects: defect_center = centroid(defect['defect_region']) outline = defect['defect_region'] ^ morphology.binary_dilation(defect['defect_region'],morphology.disk(2)) bmp[outline==1] = 255 txt = ax.annotate(DEFECT_TYPES[defect['defect_type']],(defect_center[0]-5,defect_center[1]), color='white', fontweight='bold', fontsize=10); txt.set_path_effects([PathEffects.withStroke(linewidth=2, foreground='k')]); txt_out.append(txt) unknown_td = np.multiply(unclassified_defect_region, (td_classify != 0).astype(np.int)) bmp[morphology.binary_dilation(unknown_td,morphology.disk(2))==1] = 0 bmp[morphology.binary_dilation(unknown_td,morphology.disk(1))==1] = 255 frame = ax.imshow(bmp); ax.axis('off'); return fig, ax, frame, txt_out
def plot(m): plt.figure() img=plt.imshow(m) #img.set_clim(0.0,1.0) img.set_interpolation('nearest') #plt.set_cmap('gray') plt.colorbar()
def showHistogram(image_list, name_list, path, toSave=False, hist_range=(0.0, 1.0)): """Shows the histogram of images specified by image_list and sets the range of hist() using hist_range""" fig = plt.figure() fig.subplots_adjust(hspace=.5) image_coordinate = 321 i = 0 for image in image_list: fig.add_subplot(image_coordinate) plt.title(name_list[i]) plt.set_cmap('gray') plt.axis('off') plt.imshow(image) image_coordinate += 1 fig.add_subplot(image_coordinate) plt.title('histogram') plt.hist(image.ravel(), bins=256, range=hist_range) image_coordinate += 1 i += 1 if toSave: plt.savefig("./plots/images/" + path + ".jpg") plt.show()
def showHistogram(image_list, name_list, path, toSave=False, hist_range=(0.0, 1.0)): """Shows the histogram of images specified by image_list and sets the range of hist() using hist_range""" fig = plt.figure() fig.subplots_adjust(hspace=.5) image_coordinate = 321 i = 0 for image in image_list: fig.add_subplot(image_coordinate) plt.title(name_list[i]) plt.set_cmap('gray') plt.axis('off') plt.imshow(image) image_coordinate += 1 fig.add_subplot(image_coordinate) plt.title('histogram') plt.hist(image.ravel(), bins=256, range=hist_range) image_coordinate += 1 i += 1 if toSave: plt.savefig(path + ".jpg") plt.show()
def gen_anim(self,varname,cax): plt.ion() plt.figure() plt.set_cmap('Spectral') t,z2d = self.read_crop(varname,-1) im=plt.imshow(z2d,vmin=cax[0],vmax=cax[1],extent=self.domain) plt.colorbar() for kt in range(self.nt): t,z2d=self.read_crop(varname,kt) im.set_data(z2d) plt.title('t = %4.2f'%t) #plt.draw() plt.savefig('%s_%02i.png'%(varname,kt))
def plot1(self, img, path=None, mask=None, interpolation='none', colorMap='jet', suffix=''): import matplotlib.pyplot as plt if path != None: plt.ioff() if isinstance(mask, np.ndarray): img = img[:,:] * mask plt.imshow(img, interpolation=interpolation) plt.set_cmap(colorMap) cbar = plt.colorbar() cbar.set_ticks([]) if path != None: if suffix == None: fout = osp.join(path, '{0}.png'.format(self.label)) else: fout = osp.join(path, '{0}_{1}.png'.format(self.label, suffix)) try: plt.savefig(fout) except IOError: raise IOError('in classifiers.output, no such file or directory: {0}'.format(path)) else: if suffix == None: plt.title('{0}'.format(self.label)) else: plt.title('{0} - {1}'.format(self.label, suffix)) plt.show() plt.close()
def __init__(self, global_counter, path_to_mha=None, how_many_from_one=1, saving_path='./test_data/'): if path_to_mha is None: raise NameError(' missing .mha path ') self.images = [] for i in range(0, len(path_to_mha)): self.images.append(np.array(sitk.GetArrayFromImage(sitk.ReadImage(path_to_mha[i])))) mkdir_p(saving_path) plt.set_cmap('gray') while how_many_from_one > 0: image_to_save = np.zeros((5, 216, 160)) rand_value = rnd.randint(30, len(self.images[0]) - 30) for i in range(0, len(path_to_mha)): try: image_to_save[i] = self.images[i][rand_value] except: print('ahi') print(self.images[i][rand_value].shape) print(type(self.images)) print(type(self.images)) print('*') continue print(image_to_save.shape) image_to_save = image_to_save.reshape((216 * 5, 160)) print(image_to_save.shape) # image_to_save = resize(image_to_save, (5*216, 160), mode='constant') # image_to_save = image_to_save.resize(5*216, 160) plt.imsave(saving_path + str(global_counter) + '.png', image_to_save) global_counter += 1 how_many_from_one -= 1
def sitk_show(nda, title=None, margin=0.0, dpi=40): figsize = (1 + margin) * nda.shape[0] / dpi, (1 + margin) * nda.shape[1] / dpi extent = (0, nda.shape[1], nda.shape[0], 0) fig = plt.figure(figsize=figsize, dpi=dpi) ax = fig.add_axes([margin, margin, 1 - 2*margin, 1 - 2*margin]) plt.set_cmap("gray") for k in range(0,nda.shape[2]): print "printing slice "+str(k) ax.imshow(np.squeeze(nda[:,:,k]),extent=extent,interpolation=None) plt.draw() plt.pause(0.1) #plt.waitforbuttonpress()
def run(plotIt=True): sig_halfspace = 1e-6 sig_sphere = 1e0 sig_air = 1e-8 sphere_z = -50. sphere_radius = 30. # x-direction cs = 1 nc = np.ceil(2.5*(- (sphere_z-sphere_radius))/cs) # define a mesh mesh = discretize.CylMesh([[(cs, nc)], 1, [(cs, nc)]], x0='00C') # Put the model on the mesh sigma = sig_air*np.ones(mesh.nC) # start with air cells sigma[mesh.gridCC[:, 2] < 0.] = sig_halfspace # cells below the earth # indices of the sphere sphere_ind = ( (mesh.gridCC[:, 0]**2 + (mesh.gridCC[:, 2] - sphere_z)**2) <= sphere_radius**2 ) sigma[sphere_ind] = sig_sphere # sphere if plotIt is False: return # Plot a cross section through the mesh fig, ax = plt.subplots(2, 1) # Set a nice colormap! plt.set_cmap(plt.get_cmap('viridis')) plt.colorbar(mesh.plotImage(np.log10(sigma), ax=ax[0])[0], ax=ax[0]) ax[0].set_title('mirror = False') ax[0].axis('equal') ax[0].set_xlim([-200., 200.]) plt.colorbar( mesh.plotImage(np.log10(sigma), ax=ax[1], mirror=True)[0], ax=ax[1] ) ax[1].set_title('mirror = True') ax[1].axis('equal') ax[1].set_xlim([-200., 200.]) plt.tight_layout()
def plot2D(result,par1,par2, colorMap = getColorMap(), labelSize = 15, fontSize = 10, axisHandle = None, showImediate = True): """ This function constructs a 2 dimensional marginal plot of the posterior density. This is the same plot as it is displayed in plotBayes in an unmodifyable way. The result struct is passed as result. par1 and par2 should code the two parameters to plot: 0 = threshold 1 = width 2 = lambda 3 = gamma 4 = eta Further plotting options may be passed. """ # convert strings to dimension number par1,label1 = _utils.strToDim(str(par1)) par2,label2 = _utils.strToDim(str(par2)) assert (par1 != par2), 'par1 and par2 must be different numbers to code for the parameters to plot' if axisHandle == None: axisHandle = plt.gca() try: plt.axes(axisHandle) except TypeError: raise ValueError('Invalid axes handle provided to plot in.') plt.set_cmap(colorMap) marg, _, _ = marginalize(result, np.array([par1, par2])) if par1 > par2 : marg = marg.T if 1 in marg.shape: if len(result['X1D'][par1])==1: plotMarginal(result,par2) else: plotMarginal(result,par2) else: e = [result['X1D'][par2][0], result['X1D'][par2][-1], \ result['X1D'][par1][0], result['X1D'][par1][-1]] plt.imshow(marg, extent = e) plt.ylabel(label1,fontsize = labelSize) plt.xlabel(label2,fontsize = labelSize) plt.tick_params(direction='out',right='off',top='off') for side in ['top','right']: axisHandle.spines[side].set_visible(False) plt.ticklabel_format(style='sci',scilimits=(-2,4)) if (showImediate): plt.show(0)