我们从Python开源项目中,提取了以下10个代码示例,用于说明如何使用matplotlib.gridspec()。
def SavePloat_Voxels(voxels, path, iteration): voxels = voxels[:8].__ge__(0.5) fig = plt.figure(figsize=(32, 16)) gs = gridspec.GridSpec(2, 4) gs.update(wspace=0.05, hspace=0.05) for i, sample in enumerate(voxels): x, y, z = sample.nonzero() ax = plt.subplot(gs[i], projection='3d') ax.scatter(x, y, z, zdir='z', c='red') ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_aspect('equal') plt.savefig(path + '/{}.png'.format(str(iteration).zfill(3)), bbox_inches='tight') plt.close() with open(path + '/{}.pkl'.format(str(iteration).zfill(3)), "wb") as f: pickle.dump(voxels, f, protocol=pickle.HIGHEST_PROTOCOL)
def samples_write(self, x, epoch): _, samples = self.forward(x) #pdb.set_trace() samples = samples.data.cpu().numpy()[:16] fig = plt.figure(figsize=(4, 4)) gs = gridspec.GridSpec(4, 4) gs.update(wspace=0.05, hspace=0.05) for i, sample in enumerate(samples): ax = plt.subplot(gs[i]) plt.axis('off') ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_aspect('equal') plt.imshow(sample.reshape(28, 28), cmap='Greys_r') if not os.path.exists('out/'): os.makedirs('out/') plt.savefig('out/{}.png'.format(str(epoch).zfill(3)), bbox_inches='tight') #self.c += 1 plt.close(fig)
def _tile_vertical(imgs, glimpses, boxes, n_objects, fig_size, img_size, colors): # prepare figure yy, xx = imgs.shape[0], 1 + n_objects fig_y, fig_x = fig_size img_y, img_x = img_size sy, sx = yy * img_y, n_objects + img_x gs = gridspec.GridSpec(sy, sx) fig = plt.figure(figsize=(sx * fig_x, sy * fig_y)) axes = np.empty((yy, xx), dtype=object) ii = 0 for i in xrange(yy): axes[i, 0] = plt.subplot(gs[i * img_y:(i + 1) * img_y, :img_x]) for i in xrange(yy): for j in xrange(1, xx): axes[i, j] = plt.subplot(gs[i * img_y:(i + 1) * img_y, j + img_x - 1]) # plot for r in xrange(yy): axes[r, 0].imshow(imgs[r], 'gray') for n in xrange(n_objects): for (k, v), color in izip(boxes.iteritems(), colors): y, x, h, w = boxes[k] bbox = Rectangle((x[r, n], y[r, n]), w[r, n], h[r, n], edgecolor=color, facecolor='none', label=k) axes[r, 0].add_patch(bbox) for c in xrange(1, xx): axes[r, c].imshow(glimpses[r, c - 1], 'gray') # TODO: improve len_bbox = len(boxes) if len_bbox > 1: x_offset = .25 * len_bbox axes[-1, 0].legend(bbox_to_anchor=(x_offset, -.75), ncol=len_bbox, loc='lower center') return fig, axes
def plot_figure(MA0125_true_points, MA0125_fit_points, MA0078_true_points, MA0078_fit_points): """plot_figure plots the figure comparing the two motifs. Args: MA0125_true_points: true motif params as np.array MA0125_fit_points: fit motif params as np.array MA0078_true_points: true motif params as np.array MA0078_fit_points: fit motif params as np.array """ ### PLOT FIGURE ### font = {'size' : 18} matplotlib.rc('font', **font) matplotlib.rc('xtick', labelsize=13) matplotlib.rc('ytick', labelsize=13) f1 = plt.figure(figsize=(13, 6)) gs1 = gridspec.GridSpec(1, 2) gs1.update(wspace=0.025) ax1 = plt.subplot(gs1[0]) ax2 = plt.subplot(gs1[1]) plot_comparison(ax1, (MA0125_true_points, MA0125_fit_points), "Nobox (MA0125.1)") plot_comparison(ax2, (MA0078_true_points, MA0078_fit_points), "Sox-17 (MA0078.1)") ax1.set_ylabel('Recovered Parameter') plt.setp(ax2.get_yticklabels(), visible=False) f1.savefig("2_motifs_synthetic.png",transparent=True) plt.show()
def plot(samples, figId=None, retBytes=False, shape=None): if figId is None: fig = plt.figure(figsize=(4, 4)) else: fig = plt.figure(figId, figsize=(4,4)) gs = gridspec.GridSpec(4, 4) gs.update(wspace=0.05, hspace=0.05) for i, sample in enumerate(samples): ax = plt.subplot(gs[i]) plt.axis('off') ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_aspect('equal') if shape and shape[2] == 3: rescaled = np.clip(sample, 0.0, 1.0) plt.imshow(rescaled.reshape(*shape)) else: plt.imshow(sample.reshape(28, 28), cmap='Greys_r') if retBytes: buf = io.BytesIO() plt.savefig(buf, format='png') buf.seek(0) return fig, buf return fig
def __init__(self, *args, **kwargs): super(NuPICPlotOutput, self).__init__(*args, **kwargs) # Turn matplotlib interactive mode on. plt.ion() self.dates = [] self.convertedDates = [] self.value = [] self.rawValue = [] self.allValues = [] self.allRawValues = [] self.predicted = [] self.anomalyScore = [] self.anomalyLikelihood = [] self.actualLine = None self.rawLine = None self.predictedLine = None self.anomalyScoreLine = None self.anomalyLikelihoodLine = None self.linesInitialized = False self._chartHighlights = [] fig = plt.figure(figsize=(16, 10)) gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1]) self._mainGraph = fig.add_subplot(gs[0, 0]) plt.title(self.name) plt.ylabel('Value') plt.xlabel('Date') self._anomalyGraph = fig.add_subplot(gs[1]) plt.ylabel('Percentage') plt.xlabel('Date') # Maximizes window mng = plt.get_current_fig_manager() mng.resize(800, 600) plt.tight_layout()
def _tile_horizontal(imgs, glimpses, boxes, n_objects, fig_size, img_size, colors, n_rows): nt = imgs.shape[0] size = n_rows, nt // n_rows + int(nt % n_rows != 0) n_rows = 1 + n_objects yy, xx = size[0] * n_rows, size[1] fig_y, fig_x = fig_size img_y, img_x = img_size sy, sx = size[0] * (n_objects + img_y), xx * img_x gs = gridspec.GridSpec(sy, sx) fig = plt.figure(figsize=(sx * fig_x, sy * fig_y)) axes = np.empty((yy, xx), dtype=object) ii = 0 for i in xrange(yy): if i % n_rows == 0: for j in xrange(xx): axes[i, j] = plt.subplot(gs[ii:ii + img_y, j * img_x:(j + 1) * img_x]) ii += img_y else: for j in xrange(xx): axes[i, j] = plt.subplot(gs[ii, j * img_x + img_x // 2]) ii += 1 for r in xrange(0, yy, n_rows): for c in xrange(xx): idx = (r // n_rows) * xx + c if idx < nt: axes[r, c].imshow(imgs[idx], 'gray') for n in xrange(n_objects): for (k, v), color in izip(boxes.iteritems(), colors): y, x, h, w = boxes[k] bbox = Rectangle((x[idx, n], y[idx, n]), w[idx, n], h[idx, n], edgecolor=color, facecolor='none', label=k) axes[r, c].add_patch(bbox) axes[r + 1 + n, c].imshow(glimpses[idx, n], 'gray') len_bbox = len(boxes) if len_bbox > 1: x_offset = .25 * len_bbox axes[-2, axes.shape[1] // 2].legend(bbox_to_anchor=(x_offset, -(img_y + 1)), ncol=len_bbox, loc='lower center') return fig, axes
def plot_pairs_by_layer_semdeprel_schemes2(df, pairs, majs, mfls, figname, fignum, ymin=0, ymax=100, plot_maj=True): fig = plt.figure(fignum) default_size = fig.get_size_inches() fig.set_size_inches( (default_size[0]*2.5, default_size[1]*2.5) ) outer = gridspec.GridSpec(3, 1, wspace=0.2, hspace=0.5) xsubs, ysubs = 3, 2 #f, _ = plt.subplots(ysubs, xsubs) #, sharex=True, sharey=True) #default_size = f.get_size_inches() #f.set_size_inches( (default_size[0]*1.8, default_size[1]*1.8) ) schemes = df.scheme.unique() maj_line, mfl_line = '', '' for s in range(3): inner = gridspec.GridSpecFromSubplotSpec(2, 3, subplot_spec=outer[s], wspace=0.5, hspace=1) for i, ((source, target), maj, mfl) in enumerate(zip(pairs[s], majs[s], mfls[s])): ax = plt.Subplot(fig, inner[i]) df_source_target_scheme = df[(df['source'] == source) & (df['target'] == target) & (df['scheme'] == schemes[s])] accs = get_accs_from_df(df_source_target_scheme) layers = df_source_target_scheme.layer.values hide_xlabel = True if i < (ysubs-1)*xsubs else False hide_ylabel = True if i % xsubs > 0 else False maj_line, mfl_line = plot_pair_by_layer(ax, layers, accs, maj, mfl, pretty_lang_names[source] + u"\u2192" + pretty_lang_names[target], hide_xlabel=hide_xlabel, hide_ylabel=hide_ylabel, ymin=ymin, ymax=ymax, plot_maj=plot_maj, nbins=3, delta_above=False) fig.add_subplot(ax) # hide unused axes #axarr[-1, -1].axis('off') #for ax in f.axes[len(pairs):-1]: # ax.axis('off') # if plot_maj: # f.legend([maj_line, mfl_line], ['maj', 'mfl'], loc='lower left', bbox_to_anchor=(0.8,0.1), markerscale=1.5, fontsize='medium', frameon=True, title='Legend', edgecolor='black', labelspacing=1) # else: # f.legend([mfl_line], ['mfl'], loc='lower left', bbox_to_anchor=(0.8,0.1), markerscale=1.5, fontsize='medium', frameon=True, title='Legend', edgecolor='black', labelspacing=1) #plt.tight_layout() plt.savefig(figname) return fignum + 1
def visualize(convA): if convA == None: return #imgY = 10 for i in xrange(convA.shape[1]): print i temp = convA[:,i,:,:,:] print temp.shape #k = convA.shape[1] * convA.shape[0] #j = int(round(float(k) / imgY)) gs1 = gridspec.GridSpec(temp.shape[0],temp.shape[1]) gs1.update(left=None, bottom=None, right=None, top=None, wspace=0.1, hspace=0.3) dim = max(temp.shape[0],temp.shape[1]) plt.figure(figsize=(dim,dim)) for x in xrange(temp.shape[0]): for y in xrange(temp.shape[1]): w = temp[x,y,:,:] ax = plt.subplot(gs1[x,y]) ax.imshow(w,cmap=plt.cm.gist_yarg,interpolation='nearest',aspect='auto') ax.axis('off') plt.axis('off') plt.tick_params(\ axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='off', # ticks along the bottom edge are off top='off', # ticks along the top edge are off labelbottom='off') plt.tick_params(\ axis='y', # changes apply to the y-axis which='both', # both major and minor ticks are affected left='off', right='off', # ticks along the top edge are off labelleft='off') plt.savefig('./tempImages/test_fig_' + str(i) + '.png', dpi = 100) plt.close('all') createGIF()
def plot_component(Y_NN, Lambda_CC, s_Theta_CN, r_Theta_CN, assignments_N, scale_func=lambda x: np.log(x + 1), filename=None, figsize=None, dpi=None): plt.figure(figsize=figsize, dpi=dpi) fontsize = 8 height_ratios = [4, 1] width_ratios = [1, 4] N = Y_NN.shape[0] gs = gridspec.GridSpec(2, 2, height_ratios=height_ratios, width_ratios=width_ratios) gs.update(wspace=0.025, hspace=0.025) ax1 = plt.subplot(gs[1, 0]) # Lambda ax2 = plt.subplot(gs[0, 0]) # s_Theta ax3 = plt.subplot(gs[1, 1]) # r_Theta ax4 = plt.subplot(gs[0, 1]) # Y sns.heatmap(scale_func(Lambda_CC), vmin=0, cmap='Reds', ax=ax1, cbar=False, xticklabels=range(1, C + 1), yticklabels=range(1, C + 1)) plt.setp(ax1.get_yticklabels(), fontsize=fontsize, weight='bold') plt.setp(ax1.get_xticklabels(), fontsize=fontsize, weight='bold') sns.heatmap(scale_func(s_Theta_CN.T), ax=ax2, vmin=0, cmap='Blues', yticklabels=actors[order_N], cbar=False) plt.setp(ax2.get_yticklabels(), fontsize=fontsize, rotation=0, weight='bold') ax2.set_xticklabels([]) sns.heatmap(scale_func(r_Theta_CN), ax=ax3, vmin=0, cmap='Blues', xticklabels=actors[order_N], cbar=False) plt.setp(ax3.get_xticklabels(), fontsize=fontsize, rotation=90, weight='bold') ax3.set_yticklabels([]) sns.heatmap(scale_func(Y_NN), ax=ax4, vmin=0, cmap='Reds', cbar=False) N = assignments_N.size last_assignment = assignments_N[0] for i, assignment in enumerate(assignments_N): if assignment != last_assignment: ax4.axvline(i, c='g', lw=2.) ax4.axhline(N - i, c='g', lw=2.) ax2.axhline(N - i, c='g', lw=2.) ax3.axvline(i, c='g', lw=2.) last_assignment = assignment ax4.set_xticklabels([]) ax4.set_yticklabels([]) if filename is not None: plt.savefig(filename, format='pdf', bbox_inches='tight') else: plt.show()