def make_histogram(self, data, show_axis=None, distance=True): color = colors.Category.CAT20C[0] matplotlib.rcParams.update({'font.size': 9.5}) figure = Figure(frameon=False, figsize=(4, 2), dpi=72, edgecolor=color) specs = matplotlib.gridspec.GridSpec(ncols=8, nrows=1, figure=figure) plot = figure.add_subplot(specs[0, 1:7]) plot.patch.set_alpha(1.0) adjust_spines(plot, ['left'], color) formatter = FormatStrFormatter('%g') plot.yaxis.set_major_formatter(formatter) plot.yaxis.set_major_locator(MaxNLocator(5)) if distance: plot.plot(data[:, 0], data[:, 1], lw=0.75) else: plot.vlines(data[:, 0], 0, data[:, 1]) plot.set_xlim(min(data[:, 0]), max(data[:, 0])) # Ask matplotlib to render the figure to a bitmap using the Agg backend canvas = FigureCanvasCairo(figure) width, height = canvas.get_width_height() renderer = RendererCairo(canvas.figure.dpi) renderer.set_width_height(width, height) self.plot_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) renderer.set_ctx_from_surface(self.plot_surface) canvas.figure.draw(renderer) self.show_histogram = True
def draw_matplotlib_figure(self, figure): """Draws matplotlib figure to context""" class CustomRendererCairo(RendererCairo): """Workaround for older versins with limited draw path length""" if sys.byteorder == 'little': BYTE_FORMAT = 0 # BGRA else: BYTE_FORMAT = 1 # ARGB def draw_path(self, gc, path, transform, rgbFace=None): ctx = gc.ctx transform = transform + Affine2D().scale(1.0, -1.0).\ translate(0, self.height) ctx.new_path() self.convert_path(ctx, path, transform) try: self._fill_and_stroke(ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) except AttributeError: # Workaround for some Windiws version of Cairo self._fill_and_stroke(ctx, rgbFace, gc.get_alpha()) def draw_image(self, gc, x, y, im): # bbox - not currently used rows, cols, buf = im.color_conv(self.BYTE_FORMAT) surface = cairo.ImageSurface.create_for_data( buf, cairo.FORMAT_ARGB32, cols, rows, cols * 4) ctx = gc.ctx y = self.height - y - rows ctx.save() ctx.set_source_surface(surface, x, y) if gc.get_alpha() != 1.0: ctx.paint_with_alpha(gc.get_alpha()) else: ctx.paint() ctx.restore() if pyplot is None: # Matplotlib is not installed return FigureCanvasCairo(figure) dpi = float(figure.dpi) # Set a border so that the figure is not cut off at the cell border border_x = 200 / (self.rect[2] / dpi)**2 border_y = 200 / (self.rect[3] / dpi)**2 width = (self.rect[2] - 2 * border_x) / dpi height = (self.rect[3] - 2 * border_y) / dpi figure.set_figwidth(width) figure.set_figheight(height) renderer = CustomRendererCairo(dpi) renderer.set_width_height(width, height) renderer.gc.ctx = self.context renderer.text_ctx = self.context self.context.save() self.context.translate(border_x, border_y + height * dpi) figure.draw(renderer) self.context.restore()