def render_figure_as_image(self, wFig, hFig, dpi): """ Renders a matplotlib figure using the Agg backend and stores the result in a C{wx.Image}. The arguments C{wFig} and {hFig} are the width and height of the figure, and C{dpi} is the dots-per-inch to render at. """ figure = self.figure if mat_ver < zoom_ver: old_dpi = figure.dpi.get() figure.dpi.set(dpi) old_width = figure.figwidth.get() figure.figwidth.set(wFig) old_height = figure.figheight.get() figure.figheight.set(hFig) wFig_Px = int(figure.bbox.width()) hFig_Px = int(figure.bbox.height()) agg = RendererAgg(wFig_Px, hFig_Px, Value(dpi)) else: old_dpi = figure.get_dpi() figure.set_dpi(dpi) old_width = figure.get_figwidth() figure.set_figwidth(wFig) old_height = figure.get_figheight() figure.set_figheight(hFig) old_frameon = figure.frameon figure.frameon = False wFig_Px = int(figure.bbox.width) hFig_Px = int(figure.bbox.height) agg = RendererAgg(wFig_Px, hFig_Px, dpi) figure.draw(agg) if mat_ver < zoom_ver: figure.dpi.set(old_dpi) figure.figwidth.set(old_width) figure.figheight.set(old_height) else: figure.set_dpi(old_dpi) figure.set_figwidth(old_width) figure.set_figheight(old_height) figure.frameon = old_frameon image = wx.EmptyImage(wFig_Px, hFig_Px) image.SetData(agg.tostring_rgb()) return image
def test_text_annotation_get_window_extent(): figure = Figure(dpi=100) renderer = RendererAgg(200, 200, 100) # Only text annotation annotation = Annotation('test', xy=(0, 0)) annotation.set_figure(figure) text = Text(text='test', x=0, y=0) text.set_figure(figure) bbox = annotation.get_window_extent(renderer=renderer) text_bbox = text.get_window_extent(renderer=renderer) eq_(bbox.width, text_bbox.width) eq_(bbox.height, text_bbox.height) _, _, d = renderer.get_text_width_height_descent( 'text', annotation._fontproperties, ismath=False) _, _, lp_d = renderer.get_text_width_height_descent( 'lp', annotation._fontproperties, ismath=False) below_line = max(d, lp_d) # These numbers are specific to the current implementation of Text points = bbox.get_points() eq_(points[0, 0], 0.0) eq_(points[1, 0], text_bbox.width) eq_(points[0, 1], -below_line) eq_(points[1, 1], text_bbox.height - below_line)
def chunk_limit_setup(): N = 100_000 dpi = 500 w = 5 * dpi h = 6 * dpi # just fit in the width x = np.linspace(0, w, N) # and go top-to-bottom y = np.ones(N) * h y[::2] = 0 idt = IdentityTransform() # make a renderer ra = RendererAgg(w, h, dpi) # setup the minimal gc to draw a line gc = ra.new_gc() gc.set_linewidth(1) gc.set_foreground('r') # make a Path p = Path(np.vstack((x, y)).T) # effectively disable path simplification (but leaving it "on") p.simplify_threshold = 0 return ra, gc, p, idt
def test_arrow_annotation_get_window_extent(): figure = Figure(dpi=100) figure.set_figwidth(2.0) figure.set_figheight(2.0) renderer = RendererAgg(200, 200, 100) # Text annotation with arrow annotation = Annotation('', xy=(0.0, 50.0), xytext=(50.0, 50.0), xycoords='figure pixels', arrowprops={ 'facecolor': 'black', 'width': 8, 'headwidth': 10, 'shrink': 0.0 }) annotation.set_figure(figure) annotation.draw(renderer) bbox = annotation.get_window_extent() points = bbox.get_points() eq_(bbox.width, 50.0) assert_almost_equal(bbox.height, 10.0 / 0.72) eq_(points[0, 0], 0.0) eq_(points[0, 1], 50.0 - 5 / 0.72)
def draw_quadmesh(data, obj): '''Returns the PGFPlots code for an graphics environment holding a rendering of the object. ''' content = [] # Generate file name for current object if 'img number' not in data.keys(): data['img number'] = 0 filename = os.path.join( data['output dir'], '%s_img%03d.png' % (data['base name'], data['img number'])) data['img number'] = data['img number'] + 1 # Get the dpi for rendering and store the original dpi of the figure dpi = data['dpi'] fig_dpi = obj.figure.get_dpi() obj.figure.set_dpi(dpi) # Render the object and save as png file from matplotlib.backends.backend_agg import RendererAgg cbox = obj.get_clip_box() width = int(round(cbox.extents[2])) height = int(round(cbox.extents[3])) ren = RendererAgg(width, height, dpi) obj.draw(ren) # Generate a image from the render buffer image = Image.frombuffer('RGBA', ren.get_canvas_width_height(), ren.buffer_rgba(), 'raw', 'RGBA', 0, 1) # Crop the image to the actual content (removing the the regions otherwise # used for axes, etc.) # 'image.crop' expects the crop box to specify the left, upper, right, and # lower pixel. 'cbox.extents' gives the left, lower, right, and upper # pixel. box = (int(round(cbox.extents[0])), 0, int(round(cbox.extents[2])), int(round(cbox.extents[3] - cbox.extents[1]))) cropped = image.crop(box) cropped.save(filename) # Restore the original dpi of the figure obj.figure.set_dpi(fig_dpi) # write the corresponding information to the TikZ file extent = obj.axes.get_xlim() + obj.axes.get_ylim() rel_filepath = os.path.basename(filename) if data['rel data path']: rel_filepath = os.path.join(data['rel data path'], rel_filepath) # Explicitly use \pgfimage as includegrapics command, as the default # \includegraphics fails unexpectedly in some cases content.append('\\addplot graphics [includegraphics cmd=\\pgfimage,' 'xmin=%.15g, xmax=%.15g, ' 'ymin=%.15g, ymax=%.15g] {%s};\n' % (extent + (rel_filepath, ))) return data, content
def run(self, html): self.fontsize = self.original_fontsize self.text_fig = Figure(dpi=self.dpi) self.renderer = RendererAgg(self.figwidth, self.figheight, self.dpi) self.rows, self.num_header_rows = self.parse_html(html) self.col_widths = self.calculate_col_widths() self.row_heights = self.get_row_heights() self.fig = self.create_figure() return self.print_table()
def draw_quadmesh(data, obj): """Returns the PGFPlots code for an graphics environment holding a rendering of the object. """ content = [] # Generate file name for current object filename, rel_filepath = _files.new_filename(data, "img", ".png") # Get the dpi for rendering and store the original dpi of the figure dpi = data["dpi"] fig_dpi = obj.figure.get_dpi() obj.figure.set_dpi(dpi) # Render the object and save as png file from matplotlib.backends.backend_agg import RendererAgg cbox = obj.get_clip_box() width = int(round(cbox.extents[2])) height = int(round(cbox.extents[3])) ren = RendererAgg(width, height, dpi) obj.draw(ren) # Generate a image from the render buffer image = Image.frombuffer( "RGBA", ren.get_canvas_width_height(), ren.buffer_rgba(), "raw", "RGBA", 0, 1 ) # Crop the image to the actual content (removing the the regions otherwise # used for axes, etc.) # 'image.crop' expects the crop box to specify the left, upper, right, and # lower pixel. 'cbox.extents' gives the left, lower, right, and upper # pixel. box = ( int(round(cbox.extents[0])), 0, int(round(cbox.extents[2])), int(round(cbox.extents[3] - cbox.extents[1])), ) cropped = image.crop(box) cropped.save(filename) # Restore the original dpi of the figure obj.figure.set_dpi(fig_dpi) # write the corresponding information to the TikZ file extent = obj.axes.get_xlim() + obj.axes.get_ylim() # Explicitly use \pgfimage as includegrapics command, as the default # \includegraphics fails unexpectedly in some cases ff = data["float format"] content.append( "\\addplot graphics [includegraphics cmd=\\pgfimage," f"xmin={extent[0]:{ff}}, xmax={extent[1]:{ff}}, " f"ymin={extent[2]:{ff}}, ymax={extent[3]:{ff}}] {{{rel_filepath}}};\n" ) return data, content
def create_mask(self, img=None, mask_shape=None): if mask_shape is None: self.height, self.width = img.shape[:2] else: self.height, self.width = mask_shape self.renderer = RendererAgg(self.width, self.height, 90) buf = self.renderer.buffer_rgba() arr = np.frombuffer(buf, np.uint8) self.array = arr.reshape(self.height, self.width, 4) self.mask_img.set_data(self.array) self.bbox.set_points(np.array([[0, 0], [self.width, self.height]]))
def __init__(self, html): self.original_fontsize = 22 self.fontsize = self.original_fontsize self.figwidth = 20 self.dpi = 100 self.text_fig = Figure(dpi=self.dpi) self.renderer = RendererAgg(20, 4, self.dpi) self.rows, self.num_header_rows = self.parse_html(html) self.col_widths = self.calculate_col_widths() self.row_heights = self.get_row_heights() self.fig = self.create_figure()
def write_header(self): from matplotlib.backends.backend_agg import RendererAgg try: from matplotlib.transforms import Value except ImportError: dpi = 72 else: dpi = Value(72) self.renderer = RendererAgg(self.w, self.h, dpi)
def get_renderer(self, cleared=False): l, b, w, h = self.figure.bbox.bounds key = w, h, self.figure.dpi try: self._lastKey, self.renderer except AttributeError: need_new_renderer = True else: need_new_renderer = (self._lastKey != key) if need_new_renderer: self.renderer = RendererAgg(w, h, self.figure.dpi) mixin_gl_renderer(self.renderer) self._lastKey = key elif cleared: self.renderer.clear() return self.renderer
def write_header(self, resolution=72): from matplotlib.backends.backend_agg import RendererAgg, Figure from matplotlib.backend_bases import GraphicsContextBase try: from matplotlib.transforms import Value except ImportError: dpi = resolution else: dpi = Value(resolution) self.renderer = RendererAgg(self.w, self.h, dpi) self.figure = Figure() self.gc = GraphicsContextBase() self.gc.set_linewidth(.2)
def test_empty_annotation_get_window_extent(): figure = Figure(dpi=100) figure.set_figwidth(2.0) figure.set_figheight(2.0) renderer = RendererAgg(200, 200, 100) # Text annotation with arrow annotation = Annotation( '', xy=(0.0, 50.0), xytext=(0.0, 50.0), xycoords='figure pixels') annotation.set_figure(figure) annotation.draw(renderer) bbox = annotation.get_window_extent() points = bbox.get_points() eq_(points[0, 0], 0.0) eq_(points[1, 0], 0.0) eq_(points[1, 1], 50.0) eq_(points[0, 1], 50.0)
def __init__(self, arr, reverse=True): from matplotlib.transforms import Affine2D, IdentityTransform from matplotlib.backends.backend_agg import RendererAgg self.arr = arr self.height, self.width, _ = self.arr.shape renderer = RendererAgg(self.width, self.height, 90) img = mpl.image.BboxImage(renderer.bbox) img.set_data(arr) img.draw(renderer) self.renderer = renderer if not reverse: self.trans_offset = self.trans = IdentityTransform() else: self.trans_offset = Affine2D().scale(1, -1) self.trans = Affine2D().scale(1, -1).translate(0, self.height) self.parameters = {}
def test_renderer(): from matplotlib.backends.backend_agg import RendererAgg renderer = RendererAgg(10, 20, 30) pickle.dump(renderer, BytesIO())
def _renderer(self, fd): from matplotlib.backends.backend_agg import RendererAgg dpi = 72 return RendererAgg(self.w, self.h, dpi)
def write_header(self): from matplotlib.backends.backend_agg import RendererAgg dpi = 72 self.renderer = RendererAgg(self.w, self.h, dpi)
# working directly with renderer and graphics contexts primitives from matplotlib.font_manager import FontProperties from matplotlib.backends.backend_agg import RendererAgg from matplotlib.transforms import Value # a 400x400 canvas at 72dpi canvas dpi = Value(72.0) o = RendererAgg(400, 400, dpi) # the graphics context gc = o.new_gc() # draw the background white gc.set_foreground('w') face = (1, 1, 1) # white o.draw_rectangle(gc, face, 0, 0, 400, 400) # the gc's know about color strings, and can handle any matplotlib # color arguments (hex strings, rgb, format strings, etc) gc.set_foreground('g') gc.set_linewidth(4) face = (1, 0, 0) # must be rgb o.draw_rectangle(gc, face, 10, 50, 100, 200) # draw a translucent ellipse rgb = (0, 0, 1) gc.set_alpha(0.5) o.draw_arc(gc, rgb, 100, 100, 100, 100, 360, 360, 0) # draw a dashed line gc.set_dashes(0, [5, 10])