def init_1figure9axes(self): """ 同时显示9张数据表: instructions, L1D_R_misses , L1D_W_misses , cycles , L1D_R_access , L1D_W_access , IPC , L1D_R_missRate, L1D_W_missRate :return: """ # reset status. plt.close('all') # 注:matplot里面所有中文字符都得是:u"中文"的raw格式; matplotlib.rcParams["axes.unicode_minus"] = False # figure 3x3 self.fig = plt.figure(figsize=(8, 6), dpi=80) self.grid = Grid(self.fig, rect=111, nrows_ncols=(3, 3), axes_pad=0.25, label_mode='L',) self.Instruction_ax = self.grid[0] self.Cycle_ax = self.grid[3] self.IPC_ax = self.grid[6] self.L1D_R_misses_ax = self.grid[1] self.L1D_R_access_ax = self.grid[4] self.L1D_R_missRate_ax = self.grid[7] self.L1D_W_misses_ax = self.grid[2] self.L1D_W_access_ax = self.grid[5] self.L1D_W_missRate_ax = self.grid[8] # 竖轴 self.grid[0].set_ylabel(u'分子', fontproperties=self.myfont, fontsize=12) self.grid[3].set_ylabel(u'分母', fontproperties=self.myfont, fontsize=12) self.grid[6].set_ylabel(u'除积', fontproperties=self.myfont, fontsize=12) # 横轴 self.grid[6].set_xlabel(u'IPC(Instructions/cycles)' , fontproperties=self.myfont, fontsize=12) self.grid[7].set_xlabel(u'cache(miss/Read=miss rate)' , fontproperties=self.myfont, fontsize=12) self.grid[8].set_xlabel(u'cache(Read/Write=miss rate)', fontproperties=self.myfont, fontsize=12) # figure1 4x1 self.fig1 = plt.figure(figsize=(8, 6), dpi=80) self.grid1 = Grid(self.fig1, rect=111, nrows_ncols=(4, 1), axes_pad=0.25, label_mode='L', ) self.IPC_ax_1 = self.grid1[0] self.L1D_R_missRate_ax_1 = self.grid1[1] self.L1D_W_missRate_ax_1 = self.grid1[2] self.Time_ax_1 = self.grid1[3] self.grid1[0].set_ylabel(u'L1D_W_missRate', fontproperties=self.myfont, fontsize=12) self.grid1[1].set_ylabel(u'L1D_R_missRate', fontproperties=self.myfont, fontsize=12) self.grid1[2].set_ylabel(u'IPC', fontproperties=self.myfont, fontsize=12) self.grid1[3].set_ylabel(u'time{sys/perf}', fontproperties=self.myfont, fontsize=12) # 紧致layout plt.tight_layout()
def test_grid_axes_lists(): """Test Grid axes_all, axes_row and axes_column relationship.""" fig = plt.figure() grid = Grid(fig, 111, (2, 3), direction="row") assert_array_equal(grid, grid.axes_all) assert_array_equal(grid.axes_row, np.transpose(grid.axes_column)) assert_array_equal(grid, np.ravel(grid.axes_row), "row") grid = Grid(fig, 111, (2, 3), direction="column") assert_array_equal(grid, np.ravel(grid.axes_column), "column")
def compare_figures(images, nrows_ncols, show_axis=False, fig_size=(10, 8), show_fig=True): """ Show three figures in a row, link their axes :param img_1: image to show on top left :param img_2: image to show at top right :param img_3: image to show on bottom left :param img_4: image to show on bottom right :param show_axis: if False, axes will be hide :param fig_size: size of the figure :param show_fig: show figure or not :param color_bar: if True, add color bar to the last plot :return: """ from mpl_toolkits.axes_grid1 import Grid fig = plt.figure(figsize=fig_size) grid = Grid(fig, rect=111, nrows_ncols=nrows_ncols, axes_pad=0.25, label_mode='L', share_all=True) for i, (ax, img) in enumerate(zip(grid, images)): ax.imshow(img) if not show_axis: ax.axis('off') plt.tight_layout() if show_fig: plt.show()
def prepare_order_trace_plot(s_list, row_col=(3, 2)): import matplotlib.pyplot as plt row, col = row_col n_ax = len(s_list) n_f, n_remain = divmod(n_ax, row * col) if n_remain: n_ax_list = [row * col] * n_f + [n_remain] else: n_ax_list = [row * col] * n_f from mpl_toolkits.axes_grid1 import Grid i_ax = 0 fig_list = [] ax_list = [] for n_ax in n_ax_list: fig = plt.figure() fig_list.append(fig) grid = Grid(fig, 111, (row, col), ngrids=n_ax, share_x=True) sl = slice(i_ax, i_ax + n_ax) for s, ax in zip(s_list[sl], grid): ax_list.append(ax) i_ax += n_ax return fig_list, ax_list
def view_encoded_patches(img_ids, files, patchDir, model_name, img_dir, cust_name=''): if model_name == 'unet': input_size = 572 else: input_size = 321 fig = plt.figure(figsize=(11, 2)) grid = Grid(fig, rect=111, nrows_ncols=(1, 6), axes_pad=0.1, label_mode='L') for plt_cnt, iid in enumerate(img_ids): img = np.zeros((input_size, input_size, 3), dtype=np.uint8) for cnt in range(3): img[:, :, cnt] = imageio.imread( os.path.join(patchDir, files[iid][:-1] + '_RGB{}.jpg'.format(cnt))) grid[plt_cnt].imshow(crop_center(img, 224, 224)) grid[plt_cnt].set_axis_off() plt.tight_layout() if not os.path.exists(os.path.join(img_dir, cust_name)): os.makedirs(os.path.join(img_dir, cust_name)) plt.savefig( os.path.join( img_dir, cust_name, '{}_{}.png'.format(model_name, '_'.join([str(a) for a in img_ids])))) plt.show()
def compare_figures(images, nrows_ncols, fig_size=(10, 8), show_axis=False, show_fig=True, title_list=None): """ Show images in grid pattern, link their x and y axis :param images: list of images to be displayed :param nrows_ncols: a tuple of (n_h, n_w) where n_h is #elements/row and n_w is #elements/col :param fig_size: a tuple of figure size :param show_axis: if True, each subplot will have its axis shown :param show_fig: if True, plt.show() will be called :param title_list: list of title names to be displayed on each sub images :return: """ from mpl_toolkits.axes_grid1 import Grid if title_list: assert len(title_list) == len(images) fig = plt.figure(figsize=fig_size) grid = Grid(fig, rect=111, nrows_ncols=nrows_ncols, axes_pad=0.25, label_mode='L', share_all=True) for i, (ax, img) in enumerate(zip(grid, images)): ax.imshow(img) if not show_axis: ax.axis('off') if title_list: ax.set_title(title_list[i]) plt.tight_layout() if show_fig: plt.show()
def check_readout_pattern(fig, hdu_list, axis=1): from mpl_toolkits.axes_grid1 import Grid grid = Grid(fig, 111, (len(hdu_list), 1), share_x=True, share_y=True, share_all=True, label_mode="1") smin, smax = np.inf, -np.inf for hdu, ax in zip(hdu_list, grid): p_horizontal = np.median(hdu.data, axis=axis) p_horizontal0 = np.median(p_horizontal) p_horizontal -= p_horizontal0 smin = min(smin, p_horizontal[100:-100].min()) smax = max(smax, p_horizontal[100:-100].max()) ax.plot(p_horizontal) ax.axhline(0, color="0.5") ax.locator_params(axis="y", nbins=5) ax = grid[-1] ax.set_xlim(0, len(p_horizontal)) sminmax = max(-smin, smax) ax.set_ylim(-sminmax, sminmax) if axis == 1: ax.set_xlabel("y-pixel") elif axis == 0: ax.set_xlabel("x-pixel") ax.set_ylabel("ADUs")
def images_four(imgs, save, title): from mpl_toolkits.axes_grid1 import Grid f = plt.figure(figsize=(4,4)) grid = Grid( f, rect=111, nrows_ncols=(2,2), axes_pad=0.0, label_mode='none',) for ax, im in zip(grid, imgs): ax.imshow(im) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.yaxis.set_ticks_position('none') ax.yaxis.set_ticklabels([]) ax.xaxis.set_ticks_position('none') ax.xaxis.set_ticklabels([]) ax.axis('off') f.text(.08, .52, 'AP', ha='left', va='center') f.text(.95, .52, 'AN', ha='right', va='center') f.text(.50, .95, 'distintivo', ha='center', va='top',) f.text(.50, .08, 'comum', ha='center', va='bottom',) f.text(.15, .90, 'S+', ha='left', va='top') f.text(.85, .90, 'S-', ha='right', va='top') f.text(.90, .15, 'S+', ha='right', va='bottom',) f.text(.15, .15, 'S-', ha='left', va='bottom',) if save: return save_figure(title) else: plt.show()
def test_grid_axes_position(direction): """Test positioning of the axes in Grid.""" fig = plt.figure() grid = Grid(fig, 111, (2, 2), direction=direction) loc = [ax.get_axes_locator() for ax in np.ravel(grid.axes_row)] assert loc[1]._nx > loc[0]._nx and loc[2]._ny < loc[0]._ny assert loc[0]._nx == loc[2]._nx and loc[0]._ny == loc[1]._ny assert loc[3]._nx == loc[1]._nx and loc[3]._ny == loc[2]._ny
def draw_snapshot(sites, bamfiles, color="black", min_y=30, Nsite=5): import metaseq import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import Grid Nsites_use = min(Nsite, len(sites)) # take read counts from samples ip_signals = [None]*len(bamfiles) ip_arrays = [None]*len(bamfiles) for i, bamfile in zip(range(len(bamfiles)), bamfiles): ip_signals[i] = metaseq.genomic_signal(bamfile, 'bam') ip_arrays[i] = [None]*Nsites_use for k in range(Nsites_use): ip_arrays[i][k] = ip_signals[i].local_coverage(sites[k]) # draw figure fig = plt.figure(figsize=(100, 20)) grid = Grid(fig, 142, nrows_ncols=(len(bamfiles), Nsites_use), axes_pad=0.05, direction="row", add_all=True, share_all=False, label_mode="all") ymaxs = [None]*len(bamfiles) for i in range(len(bamfiles)): for k in range(Nsites_use): grid[i*Nsites_use+k].bar(ip_arrays[i][k][0], ip_arrays[i][k][1], color=color, edgecolor=color) xmin, xmax, ymin, ymax = grid[i*Nsites_use+k].axis() ymaxs[i] = max(ymaxs[i], ymax) for i in range(len(bamfiles)): for k in range(Nsites_use): xmin, xmax, ymin, ymax = grid[i*Nsites_use+k].axis() grid[i*Nsites_use+k].axis([xmin,xmax,ymin, ymaxs[i]]) grid[i*Nsites_use+k].get_xaxis().set_visible(False) grid[i*Nsites_use+k].get_yaxis().set_visible(False) grid[i*Nsites_use+k].annotate( bamfiles[i].split('/')[-1].split('.')[0] +" [0-"+str(ymaxs[i])+"]", xy=(0,1), xytext=(10, -10), va='top', xycoords='axes fraction', textcoords='offset points', fontsize=25) if i==0: chrom = str(sites[k]).split('\t')[0] start = str(sites[k]).split('\t')[1] end = str(sites[k]).split('\t')[2].split('\n')[0] grid[i*Nsites_use+k].set_title( "Location: " + chrom + " " + start + "-" + end ) return fig
def GridPlot(self): numPlot = len(self.lc) tmp = array(self.tBins) maxCounts = max(map(max, self.lc)) + 5 maxTime = tmp.max() minTime = tmp.min() Xtxt = maxTime * .6 Ytxt = maxCounts * .7 timeAxis = tmp[:, 1] fig = plt.figure(self.fignum) #pltNum = numPlot*100 +11 grid = Grid(fig, 111, nrows_ncols=(numPlot, 1), axes_pad=0, direction='column') for i in xrange(numPlot): txtString = str(self.eBins[i][0]) + ' - ' + str( self.eBins[i][1]) + ' keV' pl, = grid[i].step(timeAxis, self.lc[i], color='k') ax = pl.get_axes() #ax.set_hatch('/') #plt.yticks(rotation=-25) ax.set_ylim(top=maxCounts) #ax.set_yticklables(ax.get_yticks(),rotation=-25) yloc = plt.MaxNLocator(10, prune='lower') ax.yaxis.set_major_locator(yloc) #ax.text(Xtxt,Ytxt,txtString) #uncomment later ax.set_ylabel(r"counts s$^{-1}$") ax.set_xlabel("Time [s]") ax.set_xlim(right=maxTime, left=minTime) #plt.xlabel('Time (s)') #plt.ylabel('Counts') self.vlineLims = [0, maxCounts] self.f2 = fig self.grid = grid #fig.tight_layout() if self.save: plt.savefig(self.fname + "_grid.pdf")
def plot_corner_latent(z, lim=3, nbins=25, show_title=True): """ Make a corner plot of standard gaussian distributed latent variables. Parameters ---------- z : latent variables, array of size (n_samples, latent_dim) lim : int, optional [description], by default 3 nbins : int, optional [description], by default 25 show_title : bool, optional [description], by default True Example ------- z = np.random.normal(size=(1000,8)) plot_corner_latent(z) """ import matplotlib as mpl from mpl_toolkits.axes_grid1 import Grid latent_dim = z.shape[1] fig = plt.figure(figsize=(latent_dim * 2, latent_dim * 2)) grid = Grid(fig, rect=111, nrows_ncols=(latent_dim, latent_dim), axes_pad=0.25, label_mode='L', share_y=False) colors = mpl.cm.jet(np.linspace(0, 1, latent_dim)) bins = nbins for i in range(latent_dim): for j in range(latent_dim): ax = grid[i * latent_dim + j] if i == j: n, _, _ = ax.hist(z[:, i], bins=bins, normed=True, color=colors[i]) ax.set_yticks([]) if show_title: ax.set_title('$z_{}$'.format(i)) if i > j: ax.hist2d(z[:, j], z[:, i], bins=bins, cmap=mpl.cm.gray) if i < j: ax.axis('off') plt.tight_layout() plt.xlim(-lim, lim)
def plotFunnelsStd(proteins, decoys, decoys_scores, outputFile): from matplotlib import pylab as plt import numpy as np fig = plt.figure(figsize=(12, 12)) N = len(proteins) sqrt_n = int(np.sqrt(N)) if N == sqrt_n * sqrt_n: nrows = int(np.sqrt(N)) ncols = int(N / nrows) else: nrows = int(np.sqrt(N)) + 1 ncols = int(N / nrows) if nrows * ncols < N: ncols += 1 from mpl_toolkits.axes_grid1 import Grid grid = Grid(fig, rect=111, nrows_ncols=(nrows, ncols), axes_pad=0.25, label_mode='L', share_x=False, share_y=False) num_proteins = [(s, int(s[1:])) for s in proteins] num_proteins = sorted(num_proteins, key=lambda x: x[1]) proteins, num_proteins = zip(*num_proteins) for n, protein in enumerate(proteins): tmscores = [] scores = [] stds = [] for decoy in decoys[protein]: tmscores.append(decoy[1]) scores.append(decoys_scores[protein][decoy[0]][0]) stds.append(decoys_scores[protein][decoy[0]][1]) grid[n].errorbar(tmscores, scores, yerr=stds, fmt='.', ecolor='r') plt.xlim(-0.1, max(tmscores) + 0.1) plt.ylim(min(scores) - 1, max(scores) + 1) grid[n].set_title(protein) #plt.tight_layout() # plt.savefig(outputFile) # plt.tick_params(axis='both', which='minor', labelsize=8) # plt.savefig(outputFile, format='png', dpi=600) plt.tight_layout() plt.savefig(outputFile, format='png', dpi=600)
def PlotLC(self): fig = plt.figure(1) grid = Grid(fig,111,nrows_ncols = (3,1), axes_pad=0.,direction='column') Step(grid[0],self.tBins,self.swift,'r',1.) Step(grid[1],self.tBins,self.nai,'b',1.) Step(grid[2],self.tBins,self.bgo,'g',1.)
def __init__(self, fig=None, nrows_ncols=(8, 4)): if fig is None: import matplotlib.pyplot as plt fig = plt.figure() from mpl_toolkits.axes_grid1 import Grid self.grid = Grid( fig, 111, # similar to subplot(111) nrows_ncols=nrows_ncols, # creates 2x2 grid of axes axes_pad=0.1, share_y=False, direction="column") # pad between axes in inch.
def check_destriper(hdu, bias_mask, vmin, vmax): destriper = Destriper() hh1 = destriper.get_destriped(hdu.data, mask=bias_mask, pattern=2048) hh2 = destriper.get_destriped(hdu.data, pattern=64, mask=bias_mask) from matplotlib.colors import Normalize from mpl_toolkits.axes_grid1 import ImageGrid, Grid fig1 = plt.figure(figsize=(13, 5)) grid = ImageGrid(fig1, 111, (1, 3), share_all=True, label_mode="1", axes_pad=0.1, cbar_mode="single") norm = Normalize(vmin=vmin, vmax=vmax) for ax, dd in zip(grid, [hdu.data, hh1, hh2]): im = ax.imshow(dd, norm=norm, origin="lower", cmap="gray_r", interpolation="none") plt.colorbar(im, cax=grid[0].cax) grid[0].set_xlabel("x-pixel") grid[0].set_ylabel("y-pixel") fig1.tight_layout() fig2 = plt.figure() grid = Grid(fig2, 111, (3, 1), share_x=True, share_y=True, share_all=True, label_mode="1", axes_pad=0.1) for ax, dd in zip(grid, [hdu.data, hh1, hh2]): s = np.median(dd[:, 1024 - 128:1024 + 128], axis=1) ax.plot(s) ax.axhline(0, color="0.5") grid[2].set_xlim(0, 2048) grid[2].set_xlabel("y-pixel") fig2.tight_layout() return fig1, fig2
def show_features(self, shape, suptitle, count=-1): maxw = np.amax(self.w.T) minw = np.amin(self.w.T) count = self._output_size if count == -1 or count > \ self._output_size else count ncols = count if count < 14 else 14 nrows = count // ncols nrows = nrows if nrows > 2 else 3 fig = plt.figure(figsize=(ncols, nrows), dpi=100) grid = Grid(fig, rect=111, nrows_ncols=(nrows, ncols), axes_pad=0.01) for i, ax in enumerate(grid): x = self.w.T[i] if i < self._input_size else np.zeros(shape) x = (x.reshape(1, -1) - minw) / maxw ax.imshow(x.reshape(*shape), cmap="Greys") ax.set_axis_off() fig.text(0.5, 1, suptitle, fontsize=20, horizontalalignment='center') fig.tight_layout() plt.show() return
def do_figure_stat_per_order(jo, calib, fig=None): # smoothed_profiles = jo["smoothed_profiles"] stats = jo["per_order"]["50%"] slit_length_arcsec = calib.slit_length_arcsec if fig is None: fig = Figure(figsize=(8, 4)) grid = Grid(fig, 111, (3, 1), share_y=False, axes_pad=0.15) ax31 = grid[0] ax32 = grid[1] ax33 = grid[2] for o, k in stats: ax31.plot(o, k["height"], "o") bg_line, = ax31.plot([o for (o, _) in stats], [_["bg"] for (o, _) in stats], color="0.8", ls="--") ax31.legend([bg_line], ["background"], loc=1) for o, k in stats: ax32.plot(o, k["equivalent_width"] * slit_length_arcsec, "o") for o, k in stats: v = (k["height"] * k["equivalent_width"] * k["slit_length_in_pixel"] * 3.5) ax33.plot(o, v**.5, "o") ax33.set_xlabel("order number") ax31.set_ylabel("peak count\n/ piexl") ax32.set_ylabel("FWHM [\"]") ax33.set_ylabel("(total counts\nper RE)^1/2") return fig
def plotPairwiseClass(X, Y, labels=None, **kwargs): X = np.array(X) Y = np.array(Y) nVariables = X.shape[1] fig = pl.figure(1, (11, 8.5)) grid = Grid( fig, 111, # similar to subplot(132) nrows_ncols=(nVariables, nVariables), axes_pad=0.0, share_all=False, label_mode="L", direction="column", ) if labels is None: labels = ['var%d' % i for i in range(nVariables)] for i in range(nVariables): for j in range(nVariables): nSub = i * (nVariables) + j print nSub if i == j: n1, bins1 = np.histogram(X[:, i][np.where(np.array(Y) == 1)], bins=20) n0, bins1 = np.histogram(X[:, i][np.where(np.array(Y) == 0)], bins=bins1) scaledata = np.max(X[:, i]) / np.max((n0, n1)) grid[nSub].plot(.5 * (bins1[0:-1] + bins1[1:]), scaledata * n1, 'b-') grid[nSub].plot(.5 * (bins1[0:-1] + bins1[1:]), scaledata * n0, 'r-') grid[nSub].text(.5, .8, labels[i]) else: grid[nSub].scatter(X[:, i], X[:, j], c=Y, alpha=0.2, linewidth=0, cmap='seismic', **kwargs) return fig
def plotFunnels(proteins, decoys, decoys_scores, outputFile): from matplotlib import pylab as plt import numpy as np fig = plt.figure(figsize=(20,20)) N = len(proteins) sqrt_n = int(np.sqrt(N)) if N==sqrt_n*sqrt_n: nrows = int(np.sqrt(N)) ncols = int(N/nrows) else: nrows = int(np.sqrt(N))+1 ncols = int(N/nrows) if nrows*ncols<N: ncols+=1 from mpl_toolkits.axes_grid1 import Grid grid = Grid(fig, rect=111, nrows_ncols=(nrows,ncols), axes_pad=0.25, label_mode='L',share_x=False,share_y=False) num_proteins = [ (s,int(s[1:])) for s in proteins] num_proteins = sorted(num_proteins, key=lambda x: x[1]) proteins, num_proteins = zip(*num_proteins) for n,protein in enumerate(proteins): tmscores = [] scores = [] for decoy in decoys[protein]: tmscores.append(decoy[1]) scores.append(decoys_scores[protein][decoy[0]]) grid[n].plot(tmscores,scores,'.') plt.xlim(-0.1, max(tmscores)+0.1) plt.ylim(min(scores)-1, max(scores)+1) grid[n].set_title(protein) #plt.tight_layout() plt.savefig(outputFile)
def plot_exp(data, stat, plot_type, figname, savefig, col='abserr'): level_name, xlabel = get_levelname_and_xlabel(plot_type) grouped = data[col].dropna().groupby(level=(level_name, 'estimation', 'knode')).agg(stat) n_params = len(grouped.groupby(level=('knode', )).groups.keys()) fig = plt.figure(figsize=(8, n_params * 3)) grid = Grid(fig, 111, nrows_ncols=(n_params, 1), add_all=True, share_all=False, label_mode='L', share_x=True, share_y=False, axes_pad=.25) for i, (param_name, param_data) in enumerate(grouped.groupby(level=('knode', ))): ax = grid[i] ax.set_ylabel(param_name) for est_name, est_data in param_data.groupby(level=['estimation']): ax.errorbar(est_data.index.get_level_values(level_name), est_data, label=est_name, lw=2., marker='o') ax.set_xlabel(xlabel) plt.legend(loc=0) title = '%s_exp_%s' % (plot_type, figname) plt.suptitle(title) if savefig: plt.savefig(title + '.png') plt.savefig(title + '.svg')
def main(): args = parseargs() if args.l: # Load layout font = load_attribute(args.l + '.font') matplotlib.rc('font', **font) graph = None if args.show or args.s: fig = plt.figure() ax_main, ax_res = Grid(fig, rect=111, nrows_ncols=(2, 1), axes_pad=0.2, label_mode='L') # ax_main.get_xaxis().set_visible(False) # div = make_axes_locatable(ax_main) # ax_res = div.append_axes('bottom', pad=0.05, label='Residuals', # size='50%') # ax_res = fig.add_subplot(212, label='Residuals') graph = (fig, (ax_main, ax_res)) f_class = args.f() control = (None, None, None) colors = iter(cm.brg(np.linspace(0, 1, len(args.i) + bool(args.c)))) if args.c: _, dat = unpack_data(args.c, args.delimiter).__next__() data = [('control', dat)] control = analysis_update(data, f_class, colors.__next__(), graph, report=False, control=control, notify=False) for path in args.i: color = colors.__next__() try: data = unpack_data(path, args.delimiter, filtr=args.filtr, split_column=args.split) analysis_update(data, f_class, color, graph, args.r, control=control, notify=True) except Exception as e: raise e print('Could not process', path, os.linesep) return None if args.s: plt.tight_layout() bname = os.path.basename(path) name = os.path.splitext(bname)[0] fig.savefig(os.path.join(args.s, name + '.png'), dpi=160, bbox_inches='tight', pad_inches=0) if args.show: plt.tight_layout() plt.show()
# 5 center init_mu,mu_index = initial_centers(image_vector,5) final_c, final_mu = Kmeans(image_vector,init_mu,100) f, ax = plt.subplots(1, 5,figsize=(12,3)) for i in range(5): ax[i].imshow(final_mu[i].reshape(28,28)) ax[i].get_xaxis().set_visible(False) ax[i].get_yaxis().set_visible(False) plt.show() # 10 center init_mu,mu_index = initial_centers(image_vector,10) final_c, final_mu = Kmeans(image_vector,init_mu,200) fig = plt.figure() grid = Grid(fig, rect=111, nrows_ncols=(2,5),axes_pad=0.1) for i in range(10): grid[i].imshow(final_mu[i].reshape(28,28)) grid[i].get_xaxis().set_visible(False) grid[i].get_yaxis().set_visible(False) plt.show() # 20 center init_mu,mu_index = initial_centers(image_vector,20) final_c, final_mu = Kmeans(image_vector,init_mu,400) fig = plt.figure() grid = Grid(fig, rect=111, nrows_ncols=(4,5),axes_pad=0.1) for i in range(20): grid[i].imshow(final_mu[i].reshape(28,28)) grid[i].get_xaxis().set_visible(False) grid[i].get_yaxis().set_visible(False)
def plot_t1t1_params(fig, conn_and_dist, assign_vect, ss, hps, MAX_DIST=10, model="LogisticDistance", MAX_CLASSES=20): """ In the same order that we would plot the latent matrix, plot the per-parameter properties hps are per-relation hps note, tragically, this wants the whole figure """ from mpl_toolkits.axes_grid1 import Grid from matplotlib import pylab assign_vect = np.array(assign_vect) canon_assign_vect = util.canonicalize_assignment(assign_vect) # create the mapping between existing and new canon_to_old = {} for i, v in enumerate(canon_assign_vect): canon_to_old[v] = assign_vect[i] CLASSES = np.sort(np.unique(canon_assign_vect)) CLASSN = len(CLASSES) if CLASSN > MAX_CLASSES: print "WARNING, TOO MANY CLASSES" CLASSN = MAX_CLASSES img_grid = Grid( fig, 111, # similar to subplot(111) nrows_ncols=(CLASSN, CLASSN), axes_pad=0.1, add_all=True, share_all=True, label_mode='L', ) if "istance" not in model: return for c1i, c1_canon in enumerate(CLASSES[:MAX_CLASSES]): for c2i, c2_canon in enumerate(CLASSES[:MAX_CLASSES]): c1 = canon_to_old[c1_canon] c2 = canon_to_old[c2_canon] ax_pos = c1i * CLASSN + c2i ax = img_grid[ax_pos] nodes_1 = np.argwhere(assign_vect == c1).flatten() nodes_2 = np.argwhere(assign_vect == c2).flatten() conn_dist_hist = [] noconn_dist_hist = [] flatten_dist_val = [] assert len(nodes_1) > 0 assert len(nodes_2) > 0 for n1 in nodes_1: for n2 in nodes_2: d = conn_and_dist[n1, n2]['distance'] if conn_and_dist[n1, n2]['link']: conn_dist_hist.append(d) else: noconn_dist_hist.append(d) flatten_dist_val.append((d, conn_and_dist[n1, n2]['link'])) flatten_dist_val = np.array(flatten_dist_val) bins = np.linspace(0, MAX_DIST, 20) fine_bins = np.linspace(0, MAX_DIST, 100) if model == "LogisticDistance" or model == "LogisticDistanceFixedLambda": # compute prob as a function of distance for this class htrue, _ = np.histogram(conn_dist_hist, bins) hfalse, _ = np.histogram(noconn_dist_hist, bins) p = htrue.astype(float) / (hfalse + htrue) ax.plot(bins[:-1], p, c='b', linewidth=3) if model == "LogisticDistance": c = ss[(c1, c2)] print "MAX_DISTANCE=", MAX_DIST, np.max(fine_bins), np.max( bins), c y = util.logistic(fine_bins, c['mu'], c['lambda']) y = y * (hps['p_max'] - hps['p_min']) + hps['p_min'] ax.plot(fine_bins, y, c='r', linewidth=2) ax.text(0, 0.2, r"mu: %3.2f" % c['mu'], fontsize=4) ax.text(0, 0.6, r"lamb: %3.2f" % c['lambda'], fontsize=4) ax.axvline(c['mu'], c='k') elif model == "LogisticDistanceFixedLambda": c = ss[(c1, c2)] y = util.logistic(fine_bins, c['mu'], hps['lambda']) y = y * (c['p_scale'] - hps['p_min']) + hps['p_min'] ax.plot(fine_bins, y, c='r') ax.text(0, 0.2, r"mu: %3.2f" % c['mu'], fontsize=4) ax.text(0, 0.6, r"lamb: %3.2f" % hps['lambda'], fontsize=4) ax.axvline(c['mu'], c='k') elif model == "ExponentialDistancePoisson": if len(flatten_dist_val) > 0: x_jitter = np.random.normal(0, 0.01, len(flatten_dist_val)) y_jitter = np.random.normal(0, 0.05, len(flatten_dist_val)) ax.scatter(flatten_dist_val[:, 0] + x_jitter, flatten_dist_val[:, 1] + y_jitter, edgecolor='none', s=2) c = ss[(c1, c2)] mu = c['mu'] rate_scale = c['rate_scale'] y = np.exp(-fine_bins / mu) y = y * rate_scale ax.plot(fine_bins, y, c='r') ax.text(0, 0.2, r"mu: %3.2f" % c['mu'], fontsize=4) ax.text(0, 0.6, r"rate_scale: %3.2f" % c['rate_scale'], fontsize=4) ax.set_ylim(-1, 20.0) ax.axvline(c['mu'], c='k') elif model == "LogisticDistancePoisson": if len(flatten_dist_val) > 0: x_jitter = np.random.normal(0, 0.01, len(flatten_dist_val)) y_jitter = np.random.normal(0, 0.05, len(flatten_dist_val)) ax.scatter(flatten_dist_val[:, 0] + x_jitter, flatten_dist_val[:, 1] + y_jitter, edgecolor='none', s=2) c = ss[(c1, c2)] y = util.logistic(fine_bins, c['mu'], hps['lambda']) y = y * (c['rate_scale'] - hps['rate_min']) + hps['rate_min'] ax.plot(fine_bins, y, c='r') ax.text(0, 1, r"mu: %3.2f" % c['mu'], fontsize=4) ax.text(0, 3, r"rate_scale: %3.2f" % c['rate_scale'], fontsize=4) ax.set_ylim(-1, 20.0) ax.axvline(c['mu'], c='k') elif model == "LinearDistance": print "MAX_DISTANCE=", MAX_DIST, np.max(fine_bins), np.max( bins) c = ss[(c1, c2)] y = util.linear_dist(fine_bins, c['p'], c['mu']) y += hps['p_min'] ax.plot(fine_bins, y, c='r') ax.set_xlim(0, MAX_DIST)
def __init__(self): self.figure = plt.figure(figsize=(6 * 0.9, 10 * 0.9)) self.ax = Grid(self.figure, rect=111, nrows_ncols=(5, 1), axes_pad = 0.0)
leg.set_in_layout(False) fig.tight_layout() plt.show() ############################################################################### # Use with AxesGrid1 # ================== # # While limited, :mod:`mpl_toolkits.axes_grid1` is also supported. from mpl_toolkits.axes_grid1 import Grid plt.close('all') fig = plt.figure() grid = Grid(fig, rect=111, nrows_ncols=(2, 2), axes_pad=0.25, label_mode='L', ) for ax in grid: example_plot(ax) ax.title.set_visible(False) plt.tight_layout() ############################################################################### # Colorbar # ======== # # If you create a colorbar with `.Figure.colorbar`, the created colorbar is # an instance of Axes, *not* Subplot, so tight_layout does not work. With # Matplotlib v1.1, you may create a colorbar as a subplot using the gridspec.
def plot_comparisons(plogs, plog_filenames, order, rows_cols = (3, 6)): # theoretical optimal mean and rate dH_mean_opt = 0.41 acc_opt = 0.65 interval = 100 xlim = (0, 20000) # determine figure size by sizes of individual subplots figsize = (rows_cols[1] * 20./6, rows_cols[0] * 12.5/3) # total acceptance rate fig_acc = pl.figure(figsize = figsize) fig_acc.suptitle("Total accumulated acceptance rate after # iteration attempts. Only showing one in each %i iterations." % interval) axgrid_acc = Grid(fig_acc, rect=111, nrows_ncols=rows_cols, axes_pad=0.25, label_mode='L') for i in range(rows_cols[0]*rows_cols[1]): j = order[i] accepted = np.cumsum(plogs[j]['acc']) accrate_full = accepted / np.arange(1, len(plogs[j]['acc'])+1) name = plog_filenames[j][43:plog_filenames[j].rfind("/")] axgrid_acc[i].set_title(name) accrate = accrate_full[::interval] iteration_nr = np.arange(0, len(accrate_full), interval) axgrid_acc[i].plot(iteration_nr, accrate, '.', label='acc.rate') axgrid_acc[i].axhline(y=acc_opt, c='brown', ls='--', label='optimal') acc200 = accepted.searchsorted(200) axgrid_acc[i].axvline(x=acc200, c='magenta', ls=':', label="200 acc'ed") axgrid_acc[i].axhline(y=accrate_full[acc200:].mean(), c='magenta', ls=':', label="mean, acc'ed > 200") axgrid_acc[i].set_ylim(0, 1) axgrid_acc[i].set_xlim(xlim) axgrid_acc[i].set_xlabel("iteration attempt #") axgrid_acc[i].set_ylabel("acceptance rate till then") pl.tight_layout() pl.subplots_adjust(top=0.9) # to make sure doesn't overlap with suptitle # windowed acceptance rate window_size = 500 fig_accwin = pl.figure(figsize = figsize) fig_accwin.suptitle("Windowed acceptance rate (accumulated over %i previous iterations) after # iteration attempts. Only showing one in each %i iterations." % (window_size, interval)) axgrid_accwin = Grid(fig_accwin, rect=111, nrows_ncols=rows_cols, axes_pad=0.25, label_mode='L') for i in range(rows_cols[0]*rows_cols[1]): j = order[i] accepted = plogs[j]['acc'] name = plog_filenames[j][43:plog_filenames[j].rfind("/")] ax = axgrid_accwin[i] plot_windowed_accrate(accepted, window_size, interval, name, ax, acc_opt = acc_opt, xlim = xlim) pl.tight_layout() pl.subplots_adjust(top=0.9) # to make sure doesn't overlap with suptitle # dH fig_dH = pl.figure(figsize = figsize) fig_dH.suptitle("dH for each iteration attempt. Only showing one in each %i iterations." % interval) axgrid_dH = Grid(fig_dH, rect=111, nrows_ncols=rows_cols, axes_pad=0.25, label_mode='L') for i in range(rows_cols[0]*rows_cols[1]): j = order[i] name = plog_filenames[j][43:plog_filenames[j].rfind("/")] axgrid_dH[i].set_title(name) axgrid_dH[i].set_yscale('log') dH_j_full = plogs[j]['dH'] dH_j = dH_j_full[::interval] pos = np.argwhere(dH_j >= 0) neg = np.argwhere(dH_j < 0) iteration_nr = np.arange(0, len(dH_j_full), interval) axgrid_dH[i].plot(iteration_nr[pos], dH_j[pos], '.b', label='dH > 0') axgrid_dH[i].plot(iteration_nr[neg], -dH_j[neg], '.r', label='-dH > 0') axgrid_dH[i].axhline(y=dH_mean_opt, c='brown', ls='--', label='optimal') accepted = np.cumsum(plogs[j]['acc']) acc200 = accepted.searchsorted(200) axgrid_dH[i].axvline(x=acc200, c='magenta', ls=':', label="200 acc'ed") axgrid_dH[i].axhline(y=plogs[j]['dH'][acc200:].mean(), c='magenta', ls=':', label="mean, acc'ed > 200") axgrid_dH[i].set_xlim(xlim) axgrid_dH[i].set_xlabel("iteration attempt #") axgrid_dH[i].set_ylabel("dH") pl.tight_layout() pl.subplots_adjust(top=0.9) # to make sure doesn't overlap with suptitle # convergence: likelihood (chi^2 for gaussian likelihood) fig_chisq = pl.figure(figsize = figsize) fig_chisq.suptitle("Convergence measure: likelihood (is chi-squared for gaussian likelihood) at beginning of iteration. Only showing one in each %i iterations." % interval) axgrid_chisq = Grid(fig_chisq, rect=111, nrows_ncols=rows_cols, axes_pad=0.25, label_mode='L') for i in range(rows_cols[0]*rows_cols[1]): j = order[i] likeli_full = plogs[j]['psi_likeli_i'] likeli = likeli_full[::interval] name = plog_filenames[j][43:plog_filenames[j].rfind("/")] axgrid_chisq[i].set_title(name) iteration_nr = np.arange(0, len(likeli_full), interval) axgrid_chisq[i].plot(iteration_nr, likeli, '.', label='likelihood') axgrid_chisq[i].set_xlim(xlim) axgrid_chisq[i].set_xlabel("iteration attempt #") axgrid_chisq[i].set_ylabel("likelihood") pl.tight_layout() pl.subplots_adjust(top=0.9) # to make sure doesn't overlap with suptitle axgrid_chisq[rows_cols[1]-1].legend() axgrid_dH[rows_cols[1]-1].legend() axgrid_acc[rows_cols[1]-1].legend() axgrid_accwin[rows_cols[1]-1].legend() return fig_acc, fig_accwin, fig_dH, fig_chisq
'ytick.labelsize': fontScale, #'text.usetex': True, 'figure.figsize': fig_size } plt.rcdefaults() plt.rcParams.update(params) plt.figure(1) #plt.tight_layout(pad=0.0) plt.clf() plt.subplots_adjust(bottom=0.2) grid = Grid(fig, (1, 1, 1), nrows_ncols=(1, 1), ngrids=1, direction='column', axes_pad=0, label_mode='L', share_all=True) rNum = 5 pressureComp,error = calc_pressure(radii[0:rNum],hi16[0:rNum],8.4,\ hiErr=hiErradii[0:rNum],vdispErr=1.4) markerSize = 5 # Pressure Component if True: plt.errorbar(radii[0:rNum - 1], pressureComp[0:rNum],
gmm_models = GaussianMixture(n_components=n_comp, covariance_type='diag') gmm_models.fit(feature_train[train_idx, :]) # compute llh for each patch city_dict = {'aus': 0, 'chi': 1, 'kit': 2, 'tyr': 3, 'vie': 4} feature_valid = feature[idx < 6, :] patch_valid = [ patch_names[i] for i in range(len(patch_names)) if idx[i] < 6 ] city_name_list = [a[:3] for a in patch_valid] city_id_list = [city_dict[a] for a in city_name_list] fig = plt.figure(figsize=(3, 8)) grid = Grid(fig, rect=111, nrows_ncols=(5, 1), axes_pad=0.25, label_mode='L', share_all=True) for test_city in range(5): test_city_feature = feature_valid[[ i for i in range(len(city_id_list)) if city_id_list[i] == test_city ], :] llh = gmm_models.score_samples(test_city_feature) ax = grid[test_city] ax.hist(llh, bins=100) ax.set_xlabel('LLH') ax.set_ylabel(city_list[test_city]) plt.suptitle(city_list[city_1]) plt.tight_layout()
fig = plt.figure() mxx = rmsdPerAtom.max() * 1.1 #figure out the geometry of the plotting window natom = rmsdPerAtom.shape[1] if natom < 49: nr, nc = 6, 8 elif natom < 97: nr, nc = 12, 8 elif natom < 151: nr, nc = 15, 10 elif natom < 193: nr, nc = 16, 12 grid = Grid(fig, rect=111, nrows_ncols=(nr, nc), axes_pad=0.05, label_mode='L') def coarseGrain(x, cg=10): return [sum(x[i * cg:i * cg + cg]) / cg for i in range(int(len(x) / cg))] def colorLine(x, y, c=None, cmap=plt.get_cmap('cool'), alpha=0.4): if c == None: c = linspace(0.0, 1.0, len(x)) c = array(c) points = array([x, y]).T.reshape(-1, 1, 2) segments = concatenate([points[:-1], points[1:]], axis=1) lc = mc.LineCollection(segments, array=c, cmap=cmap, alpha=alpha) return lc