我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.subplot()。
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 test_without_bounds(self): for coord in self.coords: coord = self.cube.coord(coord) coord.bounds = None ax = plt.subplot(111, projection=self.projection) plot = Pcolormesh(self.cube, ax, coords=self.coords) for index in range(self.cube.shape[0]): element = plot(time=index) self.assertIsInstance(element, QuadMesh) self.assertEqual(element, plot.element) self.assertIsInstance(plot.axes, GeoAxesSubplot) self.assertEqual(ax, plot.axes) for coord in self.coords: self.assertTrue(plot.subcube.coord(coord).has_bounds()) subcube = self.cube[index] for coord in self.coords: subcube.coord(coord).guess_bounds() self.assertEqual(subcube, plot.subcube)
def test_with_bounds(self): for coord in self.coords: coord = self.cube.coord(coord) if not coord.has_bounds(): coord.guess_bounds() ax = plt.subplot(111, projection=self.projection) plot = Pcolormesh(self.cube, ax, coords=self.coords) for index in range(self.cube.shape[0]): element = plot(time=index) self.assertIsInstance(element, QuadMesh) self.assertEqual(element, plot.element) self.assertIsInstance(plot.axes, GeoAxesSubplot) self.assertEqual(ax, plot.axes) for coord in self.coords: self.assertTrue(plot.subcube.coord(coord).has_bounds()) self.assertEqual(self.cube[index], plot.subcube)
def analyze(context=None, results=None): import matplotlib.pyplot as plt # Plot the portfolio and asset data. ax1 = plt.subplot(211) results.algorithm_period_return.plot(ax=ax1,color='blue',legend=u'????') ax1.set_ylabel(u'??') results.benchmark_period_return.plot(ax=ax1,color='red',legend=u'????') # Show the plot. plt.gcf().set_size_inches(18, 8) plt.show() # loading the data
def plot_labeled_images_random(image_list, label_list, categories, n, title_str, ypixels, xpixels, seed, filename): random.seed(seed) index_sample = random.sample(range(len(image_list)), n) plt.figure(figsize=(2*n, 2)) #plt.suptitle(title_str) for i, ind in enumerate(index_sample): ax = plt.subplot(1, n, i + 1) plt.imshow(image_list[ind].reshape(ypixels, xpixels)) plt.gray() ax.set_title(categories[label_list[ind]], fontsize=20) ax.get_xaxis().set_visible(False); ax.get_yaxis().set_visible(False) if 1: pylab.savefig(filename, bbox_inches='tight') else: plt.show() # plot_unlabeled_images_random: plots unlabeled images at random
def plot_unlabeled_images_random(image_list, n, title_str, ypixels, xpixels, seed, filename): random.seed(seed) index_sample = random.sample(range(len(image_list)), n) plt.figure(figsize=(2*n, 2)) plt.suptitle(title_str) for i, ind in enumerate(index_sample): ax = plt.subplot(1, n, i + 1) plt.imshow(image_list[ind].reshape(ypixels, xpixels)) plt.gray() ax.get_xaxis().set_visible(False); ax.get_yaxis().set_visible(False) if 1: pylab.savefig(filename, bbox_inches='tight') else: plt.show() # plot_compare: given test images and their reconstruction, we plot them for visual comparison
def plot_compare(x_test, decoded_imgs, filename): n = 10 plt.figure(figsize=(2*n, 4)) for i in range(n): # display original ax = plt.subplot(2, n, i + 1) plt.imshow(x_test[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # display reconstruction ax = plt.subplot(2, n, i + 1 + n) plt.imshow(decoded_imgs[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) if 1: pylab.savefig(filename, bbox_inches='tight') else: plt.show() # plot_img: plots greyscale image
def plotGeneratedImages(epoch,example=100,dim=(10,10),figsize=(10,10)): noise = np.random.normal(0,1,size=(example,randomDim)) generatedImage = generator.predict(noise) generatedImage = generatedImage.reshape(example,28,28) plt.figure(figsize=figsize) for i in range(example): plt.subplot(dim[0],dim[1],i+1) plt.imshow(generatedImage[i],interpolation='nearest',cmap='gray') '''drop the x and y axis''' plt.axis('off') plt.tight_layout() if not os.path.exists('generated_image'): os.mkdir('generated_image') plt.savefig('generated_image/wgan_generated_img_epoch_%d.png' % epoch)
def createPlot(inTree): fig = plt.figure(1, facecolor='white') fig.clf() axprops = dict(xticks=[], yticks=[]) createPlot.ax1 = plt.subplot(111, frameon=False, **axprops) #no ticks #createPlot.ax1 = plt.subplot(111, frameon=False) #ticks for demo puropses plotTree.totalW = float(getNumLeafs(inTree)) plotTree.totalD = float(getTreeDepth(inTree)) plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0; plotTree(inTree, (0.5,1.0), '') plt.show() # def createPlot(): # fig = plt.figure(1, facecolor='white') # fig.clf() # createPlot.ax1 = plt.subplot(111, frameon=True) # plotNode(U'a decision node',(0.5,0.1), (0.1,0.5), decisionNode) # plotNode(U'a leaf node',(0.8,0.1), (0.3,0.8), leafNode) # plt.show()
def plot_spatial_cluster_fig(data, covar_type_tied_labels_k): """ Creates a 3x2 plot spatial plot using labels as the color """ sns.set(context='talk', style='white') data.columns = [c.lower() for c in data.columns] fig = plt.figure() placement = {'full': {True: 1, False: 4}, 'diag': {True: 2, False: 5}, 'spher': {True: 3, False: 6}} lim_left = data['longitude'].min() lim_right = data['longitude'].max() lim_bottom = data['latitude'].min() lim_top = data['latitude'].max() for covar_type, covar_tied, labels, k in covar_type_tied_labels_k: plt.subplot(2, 3, placement[covar_type][covar_tied]) plt.scatter(data['longitude'], data['latitude'], c=labels, cmap=plt.cm.rainbow, s=10) plt.xlim(left=lim_left, right=lim_right) plt.ylim(bottom=lim_bottom, top=lim_top) plt.xticks([]) plt.yticks([]) plt.xlabel('Longitude') plt.ylabel('Latitude') plt.title('{}-{}, K={}'.format(covar_type.capitalize(), ['Untied', 'Tied'][covar_tied], k)) plt.tight_layout() return fig
def make_split(ratio, gap=0.12): import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from matplotlib.ticker import MaxNLocator cax = plt.gca() box = cax.get_position() xmin, ymin = box.xmin, box.ymin xmax, ymax = box.xmax, box.ymax gs = GridSpec(2, 1, height_ratios=[ratio, 1 - ratio], left=xmin, right=xmax, bottom=ymin, top=ymax) gs.update(hspace=gap) ax = plt.subplot(gs[0]) plt.setp(ax.get_xticklabels(), visible=False) bx = plt.subplot(gs[1], sharex=ax) return ax, bx
def plot_convergence(history, prefix='', prefix2=''): plt.figure(figsize=(8, 5)) ax = plt.subplot(111) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() plt.plot(history["TC"], '-', lw=2.5, color=tableau20[0]) x = len(history["TC"]) y = np.max(history["TC"]) plt.text(0.5 * x, 0.8 * y, "TC", fontsize=18, fontweight='bold', color=tableau20[0]) if history.has_key("additivity"): plt.plot(history["additivity"], '-', lw=2.5, color=tableau20[1]) plt.text(0.5 * x, 0.3 * y, "additivity", fontsize=18, fontweight='bold', color=tableau20[1]) plt.ylabel('TC', fontsize=12, fontweight='bold') plt.xlabel('# Iterations', fontsize=12, fontweight='bold') plt.suptitle('Convergence', fontsize=12) filename = '{}/summary/convergence{}.pdf'.format(prefix, prefix2) if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) plt.savefig(filename, bbox_inches="tight") plt.close('all') return True
def plot_grid(images,w=10,path="plan.png",verbose=False): import matplotlib.pyplot as plt l = 0 images = fix_images(images) l = len(images) h = int(math.ceil(l/w)) plt.figure(figsize=(w*1.5, h*1.5)) for i,image in enumerate(images): ax = plt.subplot(h,w,i+1) try: plt.imshow(image,interpolation='nearest',cmap='gray',) except TypeError: TypeError("Invalid dimensions for image data: image={}".format(np.array(image).shape)) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) print(path) if verbose else None plt.tight_layout() plt.savefig(path) plt.close() # contiguous image
def traffic_districution(self): data_dir = g_singletonDataFilePath.getTrainDir() df = self.load_trafficdf(data_dir) print df['traffic'].describe() # sns.distplot(self.gapdf['gap'],kde=False, bins=100); df['traffic'].plot(kind='hist', bins=100) plt.xlabel('Traffic') plt.title('Histogram of Traffic') return # def disp_gap_bydistrict(self, disp_ids = np.arange(34,67,1), cls1 = 'start_district_id', cls2 = 'time_id'): # # disp_ids = np.arange(1,34,1) # plt.figure() # by_district = self.gapdf.groupby(cls1) # size = len(disp_ids) # # size = len(by_district) # col_len = row_len = math.ceil(math.sqrt(size)) # count = 1 # for name, group in by_district: # if not name in disp_ids: # continue # plt.subplot(row_len, col_len, count) # group.groupby(cls2)['gap'].mean().plot() # count += 1 # return
def __init__(self): pass # def components(self): # plotAll = len(imageType) == 1 # options = {"direction":direction, "numbering":numbering, "annotationColor":annotationColor, "showIt":False} # fig = plt.figure(figNum) # # Determine the subplot number: 131, 121 # numPlots = 130 if plotAll else len(imageType)//2*10+100 # pltNum = 1 # fxyz = self.r(I, 'F', 'F', 'M') # if plotAll or 'Fx' in imageType: # ax_x = plt.subplot(numPlots+pltNum) # self.plotImage(fxyz[0], imageType='Fx', ax=ax_x, **options) # pltNum +=1 # if plotAll or 'Fy' in imageType: # ax_y = plt.subplot(numPlots+pltNum) # self.plotImage(fxyz[1], imageType='Fy', ax=ax_y, **options) # pltNum +=1 # if plotAll or 'Fz' in imageType: # ax_z = plt.subplot(numPlots+pltNum) # self.plotImage(fxyz[2], imageType='Fz', ax=ax_z, **options) # pltNum +=1 # if showIt: plt.show()
def display_classes(png, images, classes, ncol=4): """ Draw a number of images and their predictions Example: images = data[1][:12] classes = model.predict_classes('classes.png', images) """ fig = plt.figure() nrow = len(images) / ncol if len(images) % ncol > 0: nrow = nrow + 1 def draw(i): plt.subplot(nrow,ncol,i) plt.imshow(images[i].reshape(28,28), cmap='gray', interpolation='none') plt.title('Predicted: %s' % classes[i]) [ draw(i) for i in range(0,len(images)) ] plt.tight_layout() plt.savefig(png)
def animpingpong(self): obj=self.Object img=None if not obj.imageFromNode: img = cv2.imread(obj.imageFile) else: print "copy image ..." img = obj.imageNode.ViewObject.Proxy.img.copy() print "cpied" print " loaded" # print (obj.blockSize,obj.ksize,obj.k) # edges = cv2.Canny(img,obj.minVal,obj.maxVal) # color = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB) # edges=color # kernel = np.ones((obj.xsize,obj.ysize),np.uint8) opening = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel, iterations = obj.iterations) if True: print "zeige" cv2.imshow(obj.Label,opening) print "gezeigt" else: from matplotlib import pyplot as plt plt.subplot(121),plt.imshow(img,cmap = 'gray') plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(dst,cmap = 'gray') plt.title('Corner Image'), plt.xticks([]), plt.yticks([]) plt.show() print "fertig" self.img=opening
def animpingpong(self): obj=self.Object img=None if not obj.imageFromNode: img = cv2.imread(obj.imageFile) else: print "copy image ..." img = obj.imageNode.ViewObject.Proxy.img.copy() print "cpied" print " loaded" # print (obj.blockSize,obj.ksize,obj.k) edges = cv2.Canny(img,obj.minVal,obj.maxVal) color = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB) edges=color if True: print "zeige" cv2.imshow(obj.Label,edges) print "gezeigt" else: from matplotlib import pyplot as plt plt.subplot(121),plt.imshow(img,cmap = 'gray') plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(dst,cmap = 'gray') plt.title('Corner Image'), plt.xticks([]), plt.yticks([]) plt.show() print "fertig" self.img=edges
def animpingpong(self): obj=self.Object img=None if not obj.imageFromNode: img = cv2.imread(obj.imageFile) else: print "copy image ..." img = obj.imageNode.ViewObject.Proxy.img.copy() print "cpied" print " loaded" # print (obj.blockSize,obj.ksize,obj.k) # edges = cv2.Canny(img,obj.minVal,obj.maxVal) # color = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB) # edges=color # kernel = np.ones((obj.xsize,obj.ysize),np.uint8) closing = cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel, iterations = obj.iterations) if True: print "zeige" cv2.imshow(obj.Label,closing) print "gezeigt" else: from matplotlib import pyplot as plt plt.subplot(121),plt.imshow(img,cmap = 'gray') plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(dst,cmap = 'gray') plt.title('Corner Image'), plt.xticks([]), plt.yticks([]) plt.show() print "fertig" self.img=closing
def animpingpong(self): print self print self.Object print self.Object.Name obj=self.Object img = cv2.imread(obj.imageFile) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) gray = np.float32(gray) dst = cv2.cornerHarris(gray,3,3,0.00001) dst = cv2.dilate(dst,None) img[dst>0.01*dst.max()]=[0,0,255] from matplotlib import pyplot as plt plt.subplot(121),plt.imshow(img,cmap = 'gray') plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(dst,cmap = 'gray') plt.title('Corner Image'), plt.xticks([]), plt.yticks([]) plt.show()
def main(): rh, gh, bh, bincen, feature_vec = color_hist(image, nbins=32, bins_range=(0, 256)) # Plot a figure with all three bar charts if rh is not None: fig = plt.figure(figsize=(12, 3)) plt.subplot(131) plt.bar(bincen, rh[0]) plt.xlim(0, 256) plt.title('R Histogram') plt.subplot(132) plt.bar(bincen, gh[0]) plt.xlim(0, 256) plt.title('G Histogram') plt.subplot(133) plt.bar(bincen, bh[0]) plt.xlim(0, 256) plt.title('B Histogram') fig.tight_layout() plt.show() else: print('Your function is returning None for at least one variable...')
def _setup_axes(): plt.rcParams['toolbar'] = 'None' fig = plt.figure(figsize=(fig_size, fig_size), facecolor='w') ax = plt.subplot(111, polar=True) ax.get_yaxis().set_visible(False) # 12 labels, clockwise marks = np.linspace(360. / 12, 360, 12, endpoint=True) ax.set_thetagrids(marks, map(lambda m: int(m / 30), marks), frac=.85, size='x-large') ax.set_theta_direction(-1) ax.set_theta_offset(np.pi / 2) ax.grid(None) # These are the clock hands. We update the coordinates later. bars = ax.bar([0.0, 0.0, 0.0], lengths, width=widths, bottom=0.0, color=colors, linewidth=0) return fig, ax, bars
def preprocess_edges(self): # Calculate the sobel edge features denom = 3 * 255. grey = np.sum(self.image/denom, axis=2, keepdims=False, dtype=np.float32) sobel_x = scipy.ndimage.sobel(grey, axis=0) sobel_y = scipy.ndimage.sobel(grey, axis=1) self.edge_angles = np.arctan2(sobel_y, sobel_x) # Counterclockwise self.edge_magnitues = (sobel_x ** 2 + sobel_y ** 2) ** .5 assert(self.edge_angles.dtype == np.float32) assert(self.edge_magnitues.dtype == np.float32) if False: plt.figure("EDGES") plt.subplot(1,2,1) plt.imshow(self.edge_magnitues, interpolation='nearest') plt.title("MAG") plt.subplot(1,2,2) plt.imshow(self.edge_angles, interpolation='nearest') plt.title("ANG") plt.show()
def view_samples(self, show=True): """Displays the samples.""" if not self.samples: return # Nothing to show... plt.figure("Sample views") num = len(self.samples) rows = math.floor(num ** .5) cols = math.ceil(num / rows) for idx, img in enumerate(self.samples): plt.subplot(rows, cols, idx+1) plt.imshow(img, interpolation='nearest') if show: plt.show() # EXPERIMENT: Try breaking out each output encoder by type instead of # concatenating them all together. Each type of sensors would then get its own # HTM. Maybe keep the derivatives with their source? #
def plot_triplets(data, fig=None, colors=['r','g','b'], labels=None, linewidth=2.0, isDashed=False): ''' data: N * 3 - N samples, each being 3 Dimensional ''' if fig is None: fig = plt.figure() else: plt.figure(fig.number) N,ch = data.shape assert ch==3, 'The data is assumed to consist of 3D points' if isDashed: colors = [c + '--' for c in colors] for (i,c) in enumerate(range(ch)): plt.subplot(3,1,i+1) if labels is None: plt.plot(range(N), data[:,c], colors[c], linewidth=linewidth) else: plt.plot(range(N), data[:,c], colors[c], linewidth=linewidth, label=labels[c]) plt.legend(fontsize='large') return fig
def vis_lmdb(prms, setName='train'): db = mpio.DbReader(prms['paths']['lmdb'][setName]) plt.ion() fig = plt.figure() ax = plt.subplot(1,1,1) clNames = get_classnames(prms) N = 100 for i in range(N): im,lb = db.read_next() im = im.transpose((1,2,0)) im = im[:,:,[2,1,0]] ax.imshow(im) ax.axis('off') plt.title('Class: %s' % clNames[lb]) raw_input() ## # Make all the lmdbs
def getSSM(X, DPixels, doPlot = False): """ Compute a Euclidean self-similarity image between a set of points :param X: An Nxd matrix holding the d coordinates of N points :param DPixels: The image will be resized to this dimensions :param doPlot: If true, show a plot comparing the original/resized images :return: A tuple (D, DResized) """ D = np.sum(X**2, 1)[:, None] D = D + D.T - 2*X.dot(X.T) D[D < 0] = 0 D = 0.5*(D + D.T) D = np.sqrt(D) if doPlot: plt.subplot(121) plt.imshow(D, interpolation = 'nearest', cmap = 'afmhot') plt.subplot(122) plt.imshow(scipy.misc.imresize(D, (DPixels, DPixels)), interpolation = 'nearest', cmap = 'afmhot') plt.show() if not (D.shape[0] == DPixels): return (D, scipy.misc.imresize(D, (DPixels, DPixels))) return (D, D)
def plot(file_path, iterations): im = Image.open(file_path) im = np.array(im, dtype=np.uint8) plt.figure(figsize=(20, 16)) plt.subplot(121) plt.imshow(im) plt.axis('off') plt.subplot(122) plt.imshow(np.zeros((640, 300, 3))) height = 14 for i in range(len(labels)): plt.text(0, height * i + height / 2, labels[i], family='Times New Roman', size=14, color='#ffffff') plt.axis('off') # plt.savefig(idx) plt.show()
def cellplot(fs, csf): """ Plots PSF kernels -------------------------------------------------------------------------- Usage: Call: cellplot(fs, csf) Input: fs PSF kernels, i.e. 3d array with kernels indexed by 0th index csf size of kernels in x and y direction Output: Shows stack of PSF kernels arranged according to csf -------------------------------------------------------------------------- Copyright (C) 2011 Michael Hirsch """ mp.clf() for i in range(np.prod(csf)): mp.subplot(csf[0],csf[1],i+1) mp.imshow(fs[i]) mp.axis('off') mp.draw()
def info(self,burn=1000,plot=False): """ Print the summary statistics and optionally plot the results """ rows=len(self.varnames) cols=2 chain=np.array(self.chain[burn:]) nsize=chain.shape[0] # print rows,cols print '%4s %16s %12s %12s [%12s, %12s, %12s]'%('no','name','mean','stddev','16%','50%','84%') for i,name in enumerate(self.varnames): temp=np.percentile(chain[:,i],[16.0,84.0,50.0]) print '%4i %16s %12g %12g [%12g, %12g, %12g]'%(i,name,np.mean(chain[:,i]),(temp[1]-temp[0])/2.0,temp[0],temp[2],temp[1]) if plot: ax=plt.subplot(rows,cols,2*i+1) # plt.text(0.05,0.9,r'$\tau$='+'%5.1f'%(acor.acor(chain[:,i])[0]),transform=ax.transAxes) plt.plot(chain[:,i]) plt.ylabel(self.model.descr[name][3]) plt.xlabel('Iteration') ax=plt.subplot(rows,cols,2*i+2) plt.hist(chain[:,i],bins=100,histtype='step') plt.text(0.05,0.9,sround(np.mean(chain[:,i]),temp[0],temp[1]),transform=ax.transAxes) plt.xlabel(self.model.descr[name][3]) # plt.text(0.05,0.9,'%6g %3g (%4g-%4g)'%(np.mean(chain[:,i]),(temp[1]-temp[0])/2.0,temp[0],temp[1]),transform=ax.transAxes)
def generalBlur(srcpath, dstpath): img = cv2.imread(srcpath, 0) #???????? img1 = np.float32(img) #?????? kernel = np.ones((5,5),np.float32)/25 dst = cv2.filter2D(img1,-1,kernel) #cv2.filter2D(src,dst,kernel,auchor=(-1,-1))??? #????????????? #?????-1??????????plt.figure() plt.subplot(1,2,1), plt.imshow(img1,'gray') # plt.savefig('test1.jpg') plt.subplot(1,2,2), plt.imshow(dst,'gray') # plt.savefig('test2.jpg') plt.show() # ????
def plotSeasonBreakdown(data, trend, seasonal, residual, decompfreq, saveFigName=None): """ plots each on own subplot """ ax1 = plt.subplot(411) # print(data) plt.plot(data)#, label='Original') ax1.set_title('original') plt.legend(loc='best') ax2 = plt.subplot(412) plt.plot(trend)#, label='Trend') ax2.set_title('trend') plt.legend(loc='best') ax3 = plt.subplot(413) plt.plot(seasonal,label=str(decompfreq)) ax3.set_title('seasonality') plt.legend(loc='best') ax4 = plt.subplot(414) plt.plot(residual)#, label='Residuals') ax4.set_title('residuals') plt.legend(loc='best') plt.tight_layout() if (saveFigName == None): plt.show() else: 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 plot_depths(lab, element, depths=[0, 1, 2, 3, 4], time_to_plot=False): plt.figure() ax = plt.subplot(111) if element == 'Temperature': plt.title('Temperature at specific depths') plt.ylabel('Temperature, C') else: plt.title(element + ' concentration at specific depths') plt.ylabel('Concentration') if time_to_plot: num_of_elem = int(time_to_plot / lab.dt) else: num_of_elem = len(lab.time) t = lab.time[-num_of_elem:] plt.xlabel('Time') for depth in depths: lbl = str(depth) plt.plot(t, lab.species[element]['concentration'][int( depth / lab.dx)][-num_of_elem:], lw=3, label=lbl) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) ax.grid(linestyle='-', linewidth=0.2) return ax
def plot_times(lab, element, time_slices=[0, 1, 2, 3, 4]): plt.figure() ax = plt.subplot(111) if element == 'Temperature': plt.title('Temperature profile') plt.xlabel('Temperature, C') else: plt.title(element + ' concentration') plt.xlabel('Concentration') plt.ylabel('Depth, cm') for tms in time_slices: lbl = 'at time: %.2f ' % (tms) plt.plot(lab.species[element]['concentration'][ :, int(tms / lab.dt)], -lab.x, lw=3, label=lbl) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), ncol=2) ax.grid(linestyle='-', linewidth=0.2) return ax
def show_data(data,label): [d1,d2,d3,d4] = data.shape for slices in range(d1): for depth in range(d2): #gray() plt.figure(figsize=(8,7),dpi=98) p1 = plt.subplot(211) p1.imshow(data[slices,depth,:,:]) title_data = 'data batch:' + str(slices+1) + 'th' + ' slices: ' + str(depth+1) plt.title(title_data) p2 = plt.subplot(212) p2.imshow(label[slices,depth,:,:]) title_label = 'label batch:' + str(slices+1) + 'th' + ' slices: ' + str(depth+1) plt.title(title_label) plt.pause(0.000001) plt.close()
def wheel_radii(wheel, name): cnt = len(wheel['pattern'].keys()) if cnt == 0: return N = cnt theta = numpy.linspace(0.0, 2*numpy.pi, N, endpoint=False) radii = [item['count'] for key, item in wheel['pattern'].items()] width = numpy.pi * 2 / N ax = plt.subplot(111, projection='polar') bars = ax.bar(theta, radii, width=width, bottom=0.0) for r, theta, bar, key in zip(radii, theta, bars, [key for key, item in wheel['pattern'].items()]): bar.set_label(name) bar.set_facecolor(plt.cm.jet(r / 10.)) bar.set_alpha(0.5) if r > 0: ax.annotate( key, (theta, r), xytext=(15, 15), textcoords='offset points', arrowprops=dict(facecolor='black', shrink=0.05),) plt.title(name) plt.savefig('out/wheel_%s.png' % name, dpi=300, format='png') plt.show()
def demo2(fun): ''' Smiled Monalisa ''' p = np.array([ [186, 140], [295, 135], [208, 181], [261, 181], [184, 203], [304, 202], [213, 225], [243, 225], [211, 244], [253, 244], [195, 254], [232, 281], [285, 252] ]) q = np.array([ [186, 140], [295, 135], [208, 181], [261, 181], [184, 203], [304, 202], [213, 225], [243, 225], [207, 238], [261, 237], [199, 253], [232, 281], [279, 249] ]) image = plt.imread(os.path.join(sys.path[0], "monalisa.jpg")) plt.subplot(121) plt.axis('off') plt.imshow(image) transformed_image = fun(image, p, q, alpha=1, density=1) plt.subplot(122) plt.axis('off') plt.imshow(transformed_image) plt.tight_layout(w_pad=1.0, h_pad=1.0) plt.show()
def visualize(X, Y, classes, samples_per_class=10): nb_classes = len(classes) for y, cls in enumerate(classes): idxs = np.flatnonzero(Y == y) idxs = np.random.choice(idxs, samples_per_class, replace=False) for i, idx in enumerate(idxs): plt_idx = i * nb_classes + y + 1 plt.subplot(samples_per_class, nb_classes, plt_idx) plt.imshow(X[idx], cmap='gray') plt.axis('off') if i == 0: plt.title(cls) #plt.show() plt.savefig('img/data.png') plt.clf()
def plot(samples): width = min(12,int(np.sqrt(len(samples)))) fig = plt.figure(figsize=(width, width)) gs = gridspec.GridSpec(width, width) gs.update(wspace=0.05, hspace=0.05) for ind, sample in enumerate(samples): if ind >= width*width: break ax = plt.subplot(gs[ind]) plt.axis('off') ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_aspect('equal') sample = sample * 0.5 + 0.5 sample = np.transpose(sample, (1, 2, 0)) plt.imshow(sample) return fig
def plot_weight_histogram(model, outfile, lower=-0.25, upper=0.25): n = len(model.params) plt.clf() for (i, theano_shared_params) in enumerate(model.params): weights = theano_shared_params.get_value() values = weights.flatten() plt.subplot(n,1,i+1) frame = plt.gca() frame.axes.get_yaxis().set_ticks([]) if i != n-1: ## only keep bottom one frame.axes.get_xaxis().set_ticks([]) plt.hist(values, 100) plt.xlim(lower, upper) print(' param no. %s'%(i)) print(get_stats(theano_shared_params)) plt.savefig(outfile) print('Made plot %s'%(outfile))
def plot(sizes,plotname): fig = plt.figure(figsize=(2.0,2.0),facecolor='white') ax = plt.subplot(111) psizes = ['%1.1f%%' % (x/sum(sizes)*100) for x in sizes] labels = [x+'\n'+y for x,y in zip(LABELS,psizes)] patches = plt.pie(sizes, colors=COLORS, labels=labels, shadow=False, startangle=90, labeldistance=0.7, wedgeprops={'linewidth': 4}) for pie_wedge in patches[0]: pie_wedge.set_edgecolor('white') for t in patches[1]: t.set_horizontalalignment('center') plt.axis('equal') plt.tight_layout() plt.savefig(plotname) print('saved plot to {}'.format(plotname)) plt.show() ###################################################### # Data processing
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 plot_loss(loss_list, log_dir, iter_id): def running_mean(x, N): cumsum = np.cumsum(np.insert(x, 0, 0)) return (cumsum[N:] - cumsum[:-N]) / N plt.figure() plt.semilogy(loss_list, '.', alpha=0.2, label="Loss") plt.semilogy(running_mean(loss_list,100), label="Average Loss") plt.xlabel('Iterations') plt.ylabel('Loss') plt.legend() plt.grid() ax = plt.subplot(111) ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), ncol=3, fancybox=True, shadow=True) plt.savefig(log_dir + "/fig_loss_iter_" + str(iter_id) + ".pdf") print("figure plotted") plt.close()
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 plot_eigenvalues(d, mytitle = None, subplot_loc=None): k = d.shape[0] if subplot_loc is not None: plt.subplot(subplot_loc) plt.plot(range(0,k), d, 'b*', range(0,k), np.ones(k), '-r') plt.yscale('log') if mytitle is not None: plt.title(mytitle)
def test(self): projection = iplt.default_projection(self.cube) ax = plt.subplot(111, projection=projection) plot = Contourf(self.cube, ax, coords=self.coords) for index in range(self.cube.shape[0]): element = plot(time=index) self.assertIsInstance(element, QuadContourSet) self.assertEqual(element, plot.element) self.assertIsInstance(plot.axes, GeoAxesSubplot) self.assertEqual(ax, plot.axes) self.assertEqual(self.cube[index], plot.subcube)
def test(self): projection = iplt.default_projection(self.cube) ax = plt.subplot(111, projection=projection) plot = Contour(self.cube, ax, coords=self.coords) for index in range(self.cube.shape[0]): element = plot(time=index) self.assertIsInstance(element, QuadContourSet) self.assertEqual(element, plot.element) self.assertIsInstance(plot.axes, GeoAxesSubplot) self.assertEqual(ax, plot.axes) self.assertEqual(self.cube[index], plot.subcube)