def save(self, name, mpl_kwargs=None, canvas=None): """Choose backend and save image to disk""" from ._mpl_imports import \ FigureCanvasAgg, FigureCanvasPdf, FigureCanvasPS if mpl_kwargs is None: mpl_kwargs = {} if 'papertype' not in mpl_kwargs: mpl_kwargs['papertype'] = 'auto' suffix = get_image_suffix(name) if suffix == '': suffix = '.png' name = "%s%s" % (name, suffix) mylog.info("Saving plot %s", name) if suffix == ".png": canvas = FigureCanvasAgg(self.figure) elif suffix == ".pdf": canvas = FigureCanvasPdf(self.figure) elif suffix in (".eps", ".ps"): canvas = FigureCanvasPS(self.figure) else: mylog.warning("Unknown suffix %s, defaulting to Agg", suffix) canvas = self.canvas with matplotlib_style_context(): canvas.print_figure(name, **mpl_kwargs) return name
def save(self, name, mpl_kwargs=None, canvas=None): """Choose backend and save image to disk""" if mpl_kwargs is None: mpl_kwargs = {} if 'papertype' not in mpl_kwargs: mpl_kwargs['papertype'] = 'auto' suffix = get_image_suffix(name) if suffix == '': suffix = '.png' name = "%s%s" % (name, suffix) mylog.info("Saving plot %s", name) if suffix == ".png": canvas = FigureCanvasAgg(self.figure) elif suffix == ".pdf": canvas = FigureCanvasPdf(self.figure) elif suffix in (".eps", ".ps"): canvas = FigureCanvasPS(self.figure) else: mylog.warning("Unknown suffix %s, defaulting to Agg", suffix) canvas = self.canvas canvas.print_figure(name, **mpl_kwargs) return name
def save(self, name=None, suffix=None, mpl_kwargs=None): """saves the plot to disk. Parameters ---------- name : string The base of the filename. If name is a directory or if name is not set, the filename of the dataset is used. suffix : string Specify the image type by its suffix. If not specified, the output type will be inferred from the filename. Defaults to PNG. mpl_kwargs : dict A dict of keyword arguments to be passed to matplotlib. >>> slc.save(mpl_kwargs={'bbox_inches':'tight'}) """ names = [] if mpl_kwargs is None: mpl_kwargs = {} if name is None: name = str(self.ds) name = os.path.expanduser(name) if name[-1] == os.sep and not os.path.isdir(name): ensure_dir(name) if os.path.isdir(name) and name != str(self.ds): name = name + (os.sep if name[-1] != os.sep else '') + str(self.ds) if suffix is None: suffix = get_image_suffix(name) if suffix != '': for k, v in iteritems(self.plots): names.append(v.save(name, mpl_kwargs)) return names if hasattr(self.data_source, 'axis'): axis = self.ds.coordinates.axis_name.get( self.data_source.axis, '') else: axis = None weight = None type = self._plot_type if type in ['Projection', 'OffAxisProjection']: weight = self.data_source.weight_field if weight is not None: weight = weight[1].replace(' ', '_') if 'Cutting' in self.data_source.__class__.__name__: type = 'OffAxisSlice' for k, v in iteritems(self.plots): if isinstance(k, tuple): k = k[1] if axis: n = "%s_%s_%s_%s" % (name, type, axis, k.replace(' ', '_')) else: # for cutting planes n = "%s_%s_%s" % (name, type, k.replace(' ', '_')) if weight: n += "_%s" % (weight) if suffix != '': n = ".".join([n,suffix]) names.append(v.save(n, mpl_kwargs)) return names
def save(self, name=None, suffix=None, mpl_kwargs=None): r""" Saves a 2d profile plot. Parameters ---------- name : str The output file keyword. suffix : string Specify the image type by its suffix. If not specified, the output type will be inferred from the filename. Defaults to PNG. mpl_kwargs : dict A dict of keyword arguments to be passed to matplotlib. >>> plot.save(mpl_kwargs={'bbox_inches':'tight'}) """ names = [] if not self._plot_valid: self._setup_plots() if mpl_kwargs is None: mpl_kwargs = {} if name is None: name = str(self.profile.ds) name = os.path.expanduser(name) xfn = self.profile.x_field yfn = self.profile.y_field if isinstance(xfn, tuple): xfn = xfn[1] if isinstance(yfn, tuple): yfn = yfn[1] for f in self.profile.field_data: _f = f if isinstance(f, tuple): _f = _f[1] middle = "2d-Profile_%s_%s_%s" % (xfn, yfn, _f) splitname = os.path.split(name) if splitname[0] != '' and not os.path.isdir(splitname[0]): os.makedirs(splitname[0]) if os.path.isdir(name) and name != str(self.profile.ds): prefix = name + (os.sep if name[-1] != os.sep else '') prefix += str(self.profile.ds) else: prefix = name if suffix is None: suffix = get_image_suffix(name) if suffix != '': for k, v in iteritems(self.plots): names.append(v.save(name, mpl_kwargs)) return names else: suffix = "png" fn = "%s_%s.%s" % (prefix, middle, suffix) names.append(fn) self.plots[f].save(fn, mpl_kwargs) return names
def save(self, name=None, suffix=None, mpl_kwargs=None): r""" Saves a 1d profile plot. Parameters ---------- name : str The output file keyword. suffix : string Specify the image type by its suffix. If not specified, the output type will be inferred from the filename. Defaults to PNG. mpl_kwargs : dict A dict of keyword arguments to be passed to matplotlib. """ if not self._plot_valid: self._setup_plots() unique = set(self.plots.values()) if len(unique) < len(self.plots): iters = izip(range(len(unique)), sorted(unique)) else: iters = iteritems(self.plots) if not suffix: suffix = "png" suffix = ".%s" % suffix fullname = False if name is None: if len(self.profiles) == 1: prefix = self.profiles[0].ds else: prefix = "Multi-data" name = "%s%s" % (prefix, suffix) else: sfx = get_image_suffix(name) if sfx != '': suffix = sfx prefix = name[:name.rfind(suffix)] fullname = True else: prefix = name xfn = self.profiles[0].x_field if isinstance(xfn, tuple): xfn = xfn[1] fns = [] for uid, plot in iters: if isinstance(uid, tuple): uid = uid[1] if fullname: fns.append("%s%s" % (prefix, suffix)) else: fns.append("%s_1d-Profile_%s_%s%s" % (prefix, xfn, uid, suffix)) mylog.info("Saving %s", fns[-1]) with matplotlib_style_context(): plot.save(fns[-1], mpl_kwargs=mpl_kwargs) return fns
def save(self, name=None, mpl_kwargs=None): """saves the plot to disk. Parameters ---------- name : string The base of the filename. If name is a directory or if name is not set, the filename of the dataset is used. mpl_kwargs : dict A dict of keyword arguments to be passed to matplotlib. >>> slc.save(mpl_kwargs={'bbox_inches':'tight'}) """ names = [] if mpl_kwargs is None: mpl_kwargs = {} if name is None: name = str(self.ds) name = os.path.expanduser(name) if name[-1] == os.sep and not os.path.isdir(name): os.mkdir(name) if os.path.isdir(name) and name != str(self.ds): name = name + (os.sep if name[-1] != os.sep else '') + str(self.ds) suffix = get_image_suffix(name) if suffix != '': for k, v in self.plots.iteritems(): names.append(v.save(name, mpl_kwargs)) return names axis = self.ds.coordinates.axis_name.get( self.data_source.axis, '') weight = None type = self._plot_type if type in ['Projection', 'OffAxisProjection']: weight = self.data_source.weight_field if weight is not None: weight = weight[1].replace(' ', '_') if 'Cutting' in self.data_source.__class__.__name__: type = 'OffAxisSlice' for k, v in self.plots.iteritems(): if isinstance(k, types.TupleType): k = k[1] if axis: n = "%s_%s_%s_%s" % (name, type, axis, k.replace(' ', '_')) else: # for cutting planes n = "%s_%s_%s" % (name, type, k.replace(' ', '_')) if weight: n += "_%s" % (weight) names.append(v.save(n, mpl_kwargs)) return names
def get_canvas(name): suffix = get_image_suffix(name) if suffix == '': suffix = '.png' if suffix == ".png": canvas_cls = mpl.FigureCanvasAgg elif suffix == ".pdf": canvas_cls = mpl.FigureCanvasPdf elif suffix in (".eps", ".ps"): canvas_cls = mpl.FigureCanvasPS else: mylog.warning("Unknown suffix %s, defaulting to Agg", suffix) canvas_cls = mpl.FigureCanvasAgg return canvas_cls
def save(self, name=None, suffix=None): r""" Saves a 1d profile plot. Parameters ---------- name : str The output file keyword. suffix : string Specify the image type by its suffix. If not specified, the output type will be inferred from the filename. Defaults to PNG. """ if not self._plot_valid: self._setup_plots() unique = set(self.figures.values()) if len(unique) < len(self.figures): iters = izip(range(len(unique)), sorted(unique)) else: iters = iteritems(self.figures) if not suffix: suffix = "png" suffix = ".%s" % suffix if name is None: if len(self.profiles) == 1: prefix = self.profiles[0].ds else: prefix = "Multi-data" name = "%s%s" % (prefix, suffix) else: sfx = get_image_suffix(name) if sfx != '': suffix = sfx prefix = name[:name.rfind(suffix)] else: prefix = name xfn = self.profiles[0].x_field if isinstance(xfn, tuple): xfn = xfn[1] canvas_cls = get_canvas(name) fns = [] for uid, fig in iters: if isinstance(uid, tuple): uid = uid[1] canvas = canvas_cls(fig) fns.append("%s_1d-Profile_%s_%s%s" % (prefix, xfn, uid, suffix)) mylog.info("Saving %s", fns[-1]) canvas.print_figure(fns[-1]) return fns
def save(self, name=None): r""" Saves a 1d profile plot. Parameters ---------- name : str The output file keyword. """ if not self._plot_valid: self._setup_plots() unique = set(self.figures.values()) if len(unique) < len(self.figures): iters = izip(xrange(len(unique)), sorted(unique)) else: iters = self.figures.iteritems() if name is None: if len(self.profiles) == 1: prefix = self.profiles[0].ds else: prefix = "Multi-data" name = "%s.png" % prefix suffix = get_image_suffix(name) prefix = name[:name.rfind(suffix)] xfn = self.profiles[0].x_field if isinstance(xfn, types.TupleType): xfn = xfn[1] if not suffix: suffix = ".png" canvas_cls = get_canvas(name) fns = [] for uid, fig in iters: if isinstance(uid, types.TupleType): uid = uid[1] canvas = canvas_cls(fig) fns.append("%s_1d-Profile_%s_%s%s" % (prefix, xfn, uid, suffix)) mylog.info("Saving %s", fns[-1]) canvas.print_figure(fns[-1]) return fns
def save(self, name, mpl_kwargs=None, canvas=None): """Choose backend and save image to disk""" from ._mpl_imports import ( FigureCanvasAgg, FigureCanvasPdf, FigureCanvasPS, FigureCanvasSVG, ) if mpl_kwargs is None: mpl_kwargs = {} if "papertype" not in mpl_kwargs and LooseVersion( matplotlib.__version__ ) < LooseVersion("3.3.0"): mpl_kwargs["papertype"] = "auto" suffix = get_image_suffix(name) if suffix == "": suffix = ".png" name = f"{name}{suffix}" mylog.info("Saving plot %s", name) if suffix in _AGG_FORMATS: canvas = FigureCanvasAgg(self.figure) elif suffix in (".svg", ".svgz"): canvas = FigureCanvasSVG(self.figure) elif suffix == ".pdf": canvas = FigureCanvasPdf(self.figure) elif suffix in (".eps", ".ps"): canvas = FigureCanvasPS(self.figure) else: mylog.warning("Unknown suffix %s, defaulting to Agg", suffix) canvas = self.canvas with matplotlib_style_context(): canvas.print_figure(name, **mpl_kwargs) return name
def save(self, name, mpl_kwargs=None, canvas=None): """Choose backend and save image to disk""" if mpl_kwargs is None: mpl_kwargs = {} suffix = get_image_suffix(name) if suffix == '': suffix = '.png' name = "%s%s" % (name, suffix) mylog.info("Saving plot %s", name) if suffix == ".png": canvas = FigureCanvasAgg(self.figure) elif suffix == ".pdf": canvas = FigureCanvasPdf(self.figure) elif suffix in (".eps", ".ps"): canvas = FigureCanvasPS(self.figure) else: mylog.warning("Unknown suffix %s, defaulting to Agg", suffix) canvas = self.canvas canvas.print_figure(name, **mpl_kwargs) return name
def write_projection( data, filename, colorbar=True, colorbar_label=None, title=None, limits=None, take_log=True, figsize=(8, 6), dpi=100, cmap_name=None, extent=None, xlabel=None, ylabel=None, ): r"""Write a projection or volume rendering to disk with a variety of pretty parameters such as limits, title, colorbar, etc. write_projection uses the standard matplotlib interface to create the figure. N.B. This code only works *after* you have created the projection using the standard framework (i.e. the Camera interface or off_axis_projection). Accepts an NxM sized array representing the projection itself as well as the filename to which you will save this figure. Note that the final resolution of your image will be a product of dpi/100 * figsize. Parameters ---------- data : array_like image array as output by off_axis_projection or camera.snapshot() filename : string the filename where the data will be saved colorbar : boolean do you want a colorbar generated to the right of the image? colorbar_label : string the label associated with your colorbar title : string the label at the top of the figure limits : 2-element array_like the lower limit and the upper limit to be plotted in the figure of the data array take_log : boolean plot the log of the data array (and take the log of the limits if set)? figsize : array_like width, height in inches of final image dpi : int final image resolution in pixels / inch cmap_name : string The name of the colormap. Examples -------- >>> image = off_axis_projection(ds, c, L, W, N, "Density", no_ghost=False) >>> write_projection(image, 'test.png', colorbar_label="Column Density (cm$^{-2}$)", title="Offaxis Projection", limits=(1e-5,1e-3), take_log=True) """ if cmap_name is None: cmap_name = ytcfg.get("yt", "default_colormap") import matplotlib.colors import matplotlib.figure from ._mpl_imports import FigureCanvasAgg, FigureCanvasPdf, FigureCanvasPS # If this is rendered as log, then apply now. if take_log: norm = matplotlib.colors.LogNorm() else: norm = matplotlib.colors.Normalize() if limits is None: limits = [None, None] # Create the figure and paint the data on fig = matplotlib.figure.Figure(figsize=figsize) ax = fig.add_subplot(111) cax = ax.imshow( data.to_ndarray(), vmin=limits[0], vmax=limits[1], norm=norm, extent=extent, cmap=cmap_name, ) if title: ax.set_title(title) if xlabel: ax.set_xlabel(xlabel) if ylabel: ax.set_ylabel(ylabel) # Suppress the x and y pixel counts if extent is None: ax.set_xticks(()) ax.set_yticks(()) # Add a color bar and label if requested if colorbar: cbar = fig.colorbar(cax) if colorbar_label: cbar.ax.set_ylabel(colorbar_label) suffix = get_image_suffix(filename) if suffix == "": suffix = ".png" filename = f"{filename}{suffix}" mylog.info("Saving plot %s", filename) if suffix == ".pdf": canvas = FigureCanvasPdf(fig) elif suffix in (".eps", ".ps"): canvas = FigureCanvasPS(fig) else: canvas = FigureCanvasAgg(fig) fig.tight_layout() canvas.print_figure(filename, dpi=dpi) return filename
def save(self, fname=None, sigma_clip=None): r"""Saves the most recently rendered image of the Scene to disk. Once you have created a scene and rendered that scene to an image array, this saves that image array to disk with an optional filename. If an image has not yet been rendered for the current scene object, it forces one and writes it out. Parameters ---------- fname: string, optional If specified, save the rendering as a bitmap to the file "fname". If unspecified, it creates a default based on the dataset filename. Default: None sigma_clip: float, optional Image values greater than this number times the standard deviation plus the mean of the image will be clipped before saving. Useful for enhancing images as it gets rid of rare high pixel values. Default: None floor(vals > std_dev*sigma_clip + mean) Returns ------- Nothing Examples -------- >>> import yt >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030') >>> >>> sc = yt.create_scene(ds) >>> # Modify camera, sources, etc... >>> sc.render() >>> sc.save('test.png', sigma_clip=4) Or alternatively: >>> import yt >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030') >>> >>> sc = yt.create_scene(ds) >>> # save with different sigma clipping values >>> sc.save('raw.png') >>> sc.save('clipped_2.png', sigma_clip=2) >>> sc.save('clipped_4.png', sigma_clip=4) """ if fname is None: sources = list(itervalues(self.sources)) rensources = [s for s in sources if isinstance(s, RenderSource)] # if a volume source present, use its affiliated ds for fname if len(rensources) > 0: rs = rensources[0] basename = rs.data_source.ds.basename if isinstance(rs.field, string_types): field = rs.field else: field = rs.field[-1] fname = "%s_Render_%s.png" % (basename, field) # if no volume source present, use a default filename else: fname = "Render_opaque.png" suffix = get_image_suffix(fname) if suffix == '': suffix = '.png' fname = '%s%s' % (fname, suffix) self.render() mylog.info("Saving render %s", fname) self._last_render.write_png(fname, sigma_clip=sigma_clip)
def save(self, fname=None, sigma_clip=None): r"""Saves the most recently rendered image of the Scene to disk. Once you have created a scene and rendered that scene to an image array, this saves that image array to disk with an optional filename. If an image has not yet been rendered for the current scene object, it forces one and writes it out. Parameters ---------- fname: string, optional If specified, save the rendering as to the file "fname". If unspecified, it creates a default based on the dataset filename. The file format is inferred from the filename's suffix. Supported fomats are png, pdf, eps, and ps. Default: None sigma_clip: float, optional Image values greater than this number times the standard deviation plus the mean of the image will be clipped before saving. Useful for enhancing images as it gets rid of rare high pixel values. Default: None floor(vals > std_dev*sigma_clip + mean) Returns ------- Nothing Examples -------- >>> import yt >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030') >>> >>> sc = yt.create_scene(ds) >>> # Modify camera, sources, etc... >>> sc.render() >>> sc.save('test.png', sigma_clip=4) Or alternatively: >>> import yt >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030') >>> >>> sc = yt.create_scene(ds) >>> # save with different sigma clipping values >>> sc.save('raw.png') >>> sc.save('clipped_2.png', sigma_clip=2) >>> sc.save('clipped_4.png', sigma_clip=4) """ if fname is None: sources = list(itervalues(self.sources)) rensources = [s for s in sources if isinstance(s, RenderSource)] # if a volume source present, use its affiliated ds for fname if len(rensources) > 0: rs = rensources[0] basename = rs.data_source.ds.basename if isinstance(rs.field, string_types): field = rs.field else: field = rs.field[-1] fname = "%s_Render_%s.png" % (basename, field) # if no volume source present, use a default filename else: fname = "Render_opaque.png" suffix = get_image_suffix(fname) if suffix == '': suffix = '.png' fname = '%s%s' % (fname, suffix) self.render() mylog.info("Saving render %s", fname) # We can render pngs natively but for other formats we defer to # matplotlib. if suffix == '.png': self._last_render.write_png(fname, sigma_clip=sigma_clip) else: from matplotlib.figure import Figure from matplotlib.backends.backend_pdf import \ FigureCanvasPdf from matplotlib.backends.backend_ps import \ FigureCanvasPS shape = self._last_render.shape fig = Figure((shape[0] / 100., shape[1] / 100.)) if suffix == '.pdf': canvas = FigureCanvasPdf(fig) elif suffix in ('.eps', '.ps'): canvas = FigureCanvasPS(fig) else: raise NotImplementedError( "Unknown file suffix '{}'".format(suffix)) ax = fig.add_axes([0, 0, 1, 1]) ax.set_axis_off() out = self._last_render nz = out[:, :, :3][out[:, :, :3].nonzero()] max_val = nz.mean() + sigma_clip * nz.std() alpha = 255 * out[:, :, 3].astype('uint8') out = np.clip(out[:, :, :3] / max_val, 0.0, 1.0) * 255 out = np.concatenate([out.astype('uint8'), alpha[..., None]], axis=-1) # not sure why we need rot90, but this makes the orientation # match the png writer ax.imshow(np.rot90(out), origin='lower') canvas.print_figure(fname, dpi=100)
def save(self, fname=None, sigma_clip=None, render=True): r"""Saves a rendered image of the Scene to disk. Once you have created a scene, this saves an image array to disk with an optional filename. This function calls render() to generate an image array, unless the render parameter is set to False, in which case the most recently rendered scene is used if it exists. Parameters ---------- fname: string, optional If specified, save the rendering as to the file "fname". If unspecified, it creates a default based on the dataset filename. The file format is inferred from the filename's suffix. Supported fomats are png, pdf, eps, and ps. Default: None sigma_clip: float, optional Image values greater than this number times the standard deviation plus the mean of the image will be clipped before saving. Useful for enhancing images as it gets rid of rare high pixel values. Default: None floor(vals > std_dev*sigma_clip + mean) render: boolean, optional If True, will always render the scene before saving. If False, will use results of previous render if it exists. Default: True Returns ------- Nothing Examples -------- >>> import yt >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030') >>> >>> sc = yt.create_scene(ds) >>> # Modify camera, sources, etc... >>> sc.save('test.png', sigma_clip=4) When saving multiple images without modifying the scene (camera, sources,etc.), render=False can be used to avoid re-rendering when a scene is saved. This is useful for generating images at a range of sigma_clip values: >>> import yt >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030') >>> >>> sc = yt.create_scene(ds) >>> # save with different sigma clipping values >>> sc.save('raw.png') # The initial render call happens here >>> sc.save('clipped_2.png', sigma_clip=2, render=False) >>> sc.save('clipped_4.png', sigma_clip=4, render=False) """ if fname is None: sources = list(self.sources.values()) rensources = [s for s in sources if isinstance(s, RenderSource)] # if a volume source present, use its affiliated ds for fname if len(rensources) > 0: rs = rensources[0] basename = rs.data_source.ds.basename if isinstance(rs.field, str): field = rs.field else: field = rs.field[-1] fname = "%s_Render_%s.png" % (basename, field) # if no volume source present, use a default filename else: fname = "Render_opaque.png" suffix = get_image_suffix(fname) if suffix == "": suffix = ".png" fname = "%s%s" % (fname, suffix) render = self._sanitize_render(render) if render: self.render() mylog.info("Saving rendered image to %s", fname) # We can render pngs natively but for other formats we defer to # matplotlib. if suffix == ".png": self._last_render.write_png(fname, sigma_clip=sigma_clip) else: from matplotlib.backends.backend_pdf import FigureCanvasPdf from matplotlib.backends.backend_ps import FigureCanvasPS from matplotlib.figure import Figure shape = self._last_render.shape fig = Figure((shape[0] / 100.0, shape[1] / 100.0)) if suffix == ".pdf": canvas = FigureCanvasPdf(fig) elif suffix in (".eps", ".ps"): canvas = FigureCanvasPS(fig) else: raise NotImplementedError("Unknown file suffix '{}'".format(suffix)) ax = fig.add_axes([0, 0, 1, 1]) ax.set_axis_off() out = self._last_render nz = out[:, :, :3][out[:, :, :3].nonzero()] max_val = nz.mean() + sigma_clip * nz.std() alpha = 255 * out[:, :, 3].astype("uint8") out = np.clip(out[:, :, :3] / max_val, 0.0, 1.0) * 255 out = np.concatenate([out.astype("uint8"), alpha[..., None]], axis=-1) # not sure why we need rot90, but this makes the orientation # match the png writer ax.imshow(np.rot90(out), origin="lower") canvas.print_figure(fname, dpi=100)
def save(self, name=None, suffix=None, mpl_kwargs=None): """saves the plot to disk. Parameters ---------- name : string The base of the filename. If name is a directory or if name is not set, the filename of the dataset is used. suffix : string Specify the image type by its suffix. If not specified, the output type will be inferred from the filename. Defaults to PNG. mpl_kwargs : dict A dict of keyword arguments to be passed to matplotlib. >>> slc.save(mpl_kwargs={'bbox_inches':'tight'}) """ names = [] if mpl_kwargs is None: mpl_kwargs = {} if name is None: name = str(self.ds) name = os.path.expanduser(name) if name[-1] == os.sep and not os.path.isdir(name): try: os.mkdir(name) except OSError as e: if e.errno == errno.EEXIST: pass else: raise if os.path.isdir(name) and name != str(self.ds): name = name + (os.sep if name[-1] != os.sep else '') + str(self.ds) if suffix is None: suffix = get_image_suffix(name) if suffix != '': for k, v in iteritems(self.plots): names.append(v.save(name, mpl_kwargs)) return names axis = self.ds.coordinates.axis_name.get( self.data_source.axis, '') weight = None type = self._plot_type if type in ['Projection', 'OffAxisProjection']: weight = self.data_source.weight_field if weight is not None: weight = weight[1].replace(' ', '_') if 'Cutting' in self.data_source.__class__.__name__: type = 'OffAxisSlice' for k, v in iteritems(self.plots): if isinstance(k, tuple): k = k[1] if axis: n = "%s_%s_%s_%s" % (name, type, axis, k.replace(' ', '_')) else: # for cutting planes n = "%s_%s_%s" % (name, type, k.replace(' ', '_')) if weight: n += "_%s" % (weight) if suffix != '': n = ".".join([n,suffix]) names.append(v.save(n, mpl_kwargs)) return names
def save_annotated(self, fname=None, label_fmt=None, text_annotate=None, dpi=100, sigma_clip=None): r"""Saves the most recently rendered image of the Scene to disk, including an image of the transfer function and and user-defined text. Once you have created a scene and rendered that scene to an image array, this saves that image array to disk with an optional filename. If an image has not yet been rendered for the current scene object, it forces one and writes it out. Parameters ---------- fname: string, optional If specified, save the rendering as a bitmap to the file "fname". If unspecified, it creates a default based on the dataset filename. Default: None sigma_clip: float, optional Image values greater than this number times the standard deviation plus the mean of the image will be clipped before saving. Useful for enhancing images as it gets rid of rare high pixel values. Default: None floor(vals > std_dev*sigma_clip + mean) dpi: integer, optional By default, the resulting image will be the same size as the camera parameters. If you supply a dpi, then the image will be scaled accordingly (from the default 100 dpi) label_fmt : str, optional A format specifier (e.g., label_fmt="%.2g") to use in formatting the data values that label the transfer function colorbar. text_annotate : list of iterables Any text that you wish to display on the image. This should be an list containing a tuple of coordinates (in normalized figure coordinates), the text to display, and, optionally, a dictionary of keyword/value pairs to pass through to the matplotlib text() function. Each item in the main list is a separate string to write. Returns ------- Nothing Examples -------- >>> sc.save_annotated("fig.png", ... text_annotate=[[(0.05, 0.05), ... "t = {}".format(ds.current_time.d), ... dict(horizontalalignment="left")], ... [(0.5,0.95), ... "simulation title", ... dict(color="y", fontsize="24", ... horizontalalignment="center")]]) """ from yt.visualization._mpl_imports import \ FigureCanvasAgg, FigureCanvasPdf, FigureCanvasPS sources = list(itervalues(self.sources)) rensources = [s for s in sources if isinstance(s, RenderSource)] if fname is None: # if a volume source present, use its affiliated ds for fname if len(rensources) > 0: rs = rensources[0] basename = rs.data_source.ds.basename if isinstance(rs.field, string_types): field = rs.field else: field = rs.field[-1] fname = "%s_Render_%s.png" % (basename, field) # if no volume source present, use a default filename else: fname = "Render_opaque.png" suffix = get_image_suffix(fname) if suffix == '': suffix = '.png' fname = '%s%s' % (fname, suffix) self.render() # which transfer function? rs = rensources[0] tf = rs.transfer_function label = rs.data_source.ds._get_field_info(rs.field).get_label() ax = self._show_mpl(self._last_render.swapaxes(0, 1), sigma_clip=sigma_clip, dpi=dpi) self._annotate(ax.axes, tf, rs, label=label, label_fmt=label_fmt) # any text? if text_annotate is not None: f = self._render_figure for t in text_annotate: xy = t[0] string = t[1] if len(t) == 3: opt = t[2] else: opt = dict() # sane default if "color" not in opt: opt["color"] = "w" ax.axes.text(xy[0], xy[1], string, transform=f.transFigure, **opt) suffix = get_image_suffix(fname) if suffix == ".png": canvas = FigureCanvasAgg(self._render_figure) elif suffix == ".pdf": canvas = FigureCanvasPdf(self._render_figure) elif suffix in (".eps", ".ps"): canvas = FigureCanvasPS(self._render_figure) else: mylog.warning("Unknown suffix %s, defaulting to Agg", suffix) canvas = self.canvas self._render_figure.canvas = canvas self._render_figure.tight_layout() self._render_figure.savefig(fname, facecolor='black', pad_inches=0)
def save(self, name=None, suffix=None, mpl_kwargs=None): """saves the plot to disk. Parameters ---------- name : string or tuple The base of the filename. If name is a directory or if name is not set, the filename of the dataset is used. For a tuple, the resulting path will be given by joining the elements of the tuple suffix : string Specify the image type by its suffix. If not specified, the output type will be inferred from the filename. Defaults to PNG. mpl_kwargs : dict A dict of keyword arguments to be passed to matplotlib. >>> slc.save(mpl_kwargs={'bbox_inches':'tight'}) """ names = [] if mpl_kwargs is None: mpl_kwargs = {} if isinstance(name, (tuple, list)): name = os.path.join(*name) if name is None: name = str(self.ds) name = os.path.expanduser(name) if name[-1] == os.sep and not os.path.isdir(name): ensure_dir(name) if os.path.isdir(name) and name != str(self.ds): name = name + (os.sep if name[-1] != os.sep else "") + str(self.ds) if suffix is None: suffix = get_image_suffix(name) if suffix != "": for v in self.plots.values(): names.append(v.save(name, mpl_kwargs)) return names if hasattr(self.data_source, "axis"): axis = self.ds.coordinates.axis_name.get(self.data_source.axis, "") else: axis = None weight = None type = self._plot_type if type in ["Projection", "OffAxisProjection"]: weight = self.data_source.weight_field if weight is not None: weight = weight[1].replace(" ", "_") if "Cutting" in self.data_source.__class__.__name__: type = "OffAxisSlice" for k, v in self.plots.items(): if isinstance(k, tuple): k = k[1] if axis: n = f"{name}_{type}_{axis}_{k.replace(' ', '_')}" else: # for cutting planes n = f"{name}_{type}_{k.replace(' ', '_')}" if weight: n += f"_{weight}" if suffix != "": n = ".".join([n, suffix]) names.append(v.save(n, mpl_kwargs)) return names