def adjust_layout(self, event: Optional[Event] = None, *, refresh_canvas: bool = False) -> None: """Optimize subplot grid and buttons width for best fit, then adjust layout based on window size. :param event: Event spent by figure `mpl_connect` 'resize_event'. :param refresh_canvas: Force redrawing figure canvas. """ # Compute figure area for later export bbox = Bbox([[0.0, 0.065], [1.0, 1.0]]) bbox_pixels = bbox.transformed(self.figure.transFigure) self.bbox_inches = bbox_pixels.transformed( self.figure.dpi_scale_trans.inverted()) # Refresh button size, in case the number of tabs has changed buttons_width = 1.0 / (len(self.tabs_data) + 1) for i, tab in enumerate(self.tabs_data.values()): tab["button_axcut"].set_position( [buttons_width * (i + 0.5), 0.01, buttons_width, 0.05]) # Re-arrange subplots in case figure aspect ratio has changed axes = self.tab_active["axes"] num_subplots = len(axes) figure_extent = self.figure.get_window_extent() figure_ratio = figure_extent.width / figure_extent.height num_rows_1 = max(1, floor(sqrt(num_subplots / figure_ratio))) num_cols_1 = ceil(num_subplots / num_rows_1) num_cols_2 = ceil(sqrt(num_subplots * figure_ratio)) num_rows_2 = ceil(num_subplots / num_cols_2) if num_rows_1 * num_cols_1 < num_rows_2 * num_cols_2: num_rows, num_cols = map(int, (num_rows_1, num_cols_1)) else: num_rows, num_cols = map(int, (num_rows_2, num_cols_2)) for i, ax in enumerate(axes, 1): ax.change_geometry(num_rows, num_cols, i) # Adjust layout: namely margins between subplots right_margin = 0.03 if self.legend is not None: legend_extent = self.legend.get_window_extent() legend_width_rel = legend_extent.transformed( self.figure.transFigure.inverted()).width right_margin += legend_width_rel self.figure.subplots_adjust( bottom=0.10, top=0.92, left=0.04, right=1.0-right_margin, wspace=0.40, hspace=0.30) # Refresh figure canvas if requested if refresh_canvas: self.refresh()
vert = tag_path.vertices - dims / 2. mult = tagline_scale_fudge * (plot_dims / dims).min() mult = [mult, -mult] # y axis is inverted offset = mne_corners[-1] - np.array([mne_clip.get_extents().size[0] / 2., -dims[1]]) - tagline_offset_fudge tag_clip = Path(offset + vert * mult, tag_path.codes) tag_patch = PathPatch(tag_clip, facecolor='k', edgecolor='none', zorder=10) ax.add_patch(tag_patch) yl = ax.get_ylim() yy = np.max([tag_clip.vertices.max(0)[-1], tag_clip.vertices.min(0)[-1]]) ax.set_ylim(np.ceil(yy), yl[-1]) # only save actual image extent plus a bit of padding extent = Bbox(np.c_[ax.get_xlim(), ax.get_ylim()]) extent = extent.transformed(ax.transData + fig.dpi_scale_trans.inverted()) plt.draw() plt.savefig(op.join(static_dir, 'mne_logo.png'), bbox_inches=extent.expanded(1.2, 1.)) plt.close() # 92x22 image w_px = 92 h_px = 22 center_fudge = np.array([12, 0.5]) scale_fudge = 2.1 rcParams.update({'font.sans-serif': ['Primetime'], 'font.weight': 'black'}) x = np.linspace(-8., 8., w_px / 2.) y = np.linspace(-3., 3., h_px / 2.) X, Y = np.meshgrid(x, y) # initialize figure (no axes, margins, etc)
def event_plot(events, rowHeight=100): genes = numpy.unique( numpy.char.partition(events.rownames.astype(str), "_")[:, 0]) x = pandas.DataFrame(numpy.zeros((len(genes), events.shape[1]), dtype=int), index=numpy.array(genes), columns=events.colnames) fig = plt.gcf() bbox = Bbox([[0.8 * fig.dpi, 0.5 * fig.dpi], [(fig.get_figwidth() - 0.5) * fig.dpi, 0.3 * len(x) * fig.dpi]]) plt.axes(bbox.transformed(plt.gcf().transFigure.inverted()).bounds) for feature in events.rownames: gene, eventType = feature.split("_", 1) i = genes.searchsorted(gene) if eventType == "mut": shift = 0 elif eventType == "gain": shift = 1 elif eventType == "loss": shift = 2 x.values[i] |= events[[feature]].events[0].astype(int) << shift geneOrder = (x.values > 0).sum(1).argsort() sampleOrder = numpy.lexsort(x.values[geneOrder])[::-1] colours = matplotlib.colors.ListedColormap( ["#dddddd", "#377eb8", "#2ca25f", "#756bb1", "#de2d26", "#ff7f00"]) plt.imshow(x.values[geneOrder][:, sampleOrder], aspect="auto", interpolation="none", cmap=colours, origin="lower", vmin=0, vmax=5) plt.grid(ls="-", c="white", axis="x") plt.setp(plt.gca().spines.values(), color="#888888", alpha=0) for tic in plt.gca().xaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False for tic in plt.gca().yaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False try: plt.yticks(numpy.arange(len(x)), x.index[geneOrder]) except AttributeError: pass plt.gca().yaxis.set_minor_locator( matplotlib.ticker.FixedLocator( numpy.linspace(-0.5, len(x) - 0.5, x.shape[0] + 1))) plt.grid(ls="-", c="white", axis="y", lw=4, alpha=1, which="minor") plt.grid(ls="None", axis="y", which="major") for tic in plt.gca().yaxis.get_minor_ticks(): tic.tick1On = tic.tick2On = False plt.gcf().patch.set_facecolor("white") plt.xlim(0, x.ix[genes].any(0).sum())