Ejemplo n.º 1
0
 def _repr_html_(self):
     ret = ''
     for k, v in self.plots.iteritems():
         canvas = FigureCanvasAgg(v)
         f = StringIO()
         canvas.print_figure(f)
         f.seek(0)
         img = base64.b64encode(f.read())
         ret += '<img src="data:image/png;base64,%s"><br>' % img
     return ret
Ejemplo n.º 2
0
 def _repr_html_(self):
     ret = ''
     for k, v in self.plots.items():
         canvas = FigureCanvasAgg(v)
         f = IO()
         canvas.print_figure(f)
         f.seek(0)
         img = base64.b64encode(f.read()).decode()
         ret += r'<img style="max-width:100%%;max-height:100%%;" ' \
                r'src="data:image/png;base64,%s"><br>' % img
     return ret
Ejemplo n.º 3
0
 def _repr_html_(self):
     ret = ''
     for k, v in self.plots.items():
         canvas = FigureCanvasAgg(v)
         f = IO()
         canvas.print_figure(f)
         f.seek(0)
         img = base64.b64encode(f.read()).decode()
         ret += r'<img style="max-width:100%%;max-height:100%%;" ' \
                r'src="data:image/png;base64,%s"><br>' % img
     return ret
Ejemplo n.º 4
0
Archivo: misc.py Proyecto: cevans216/yt
    def _repr_html_(self):
        from yt.visualization._mpl_imports import FigureCanvasAgg

        ret = ""
        for k, v in self.plots.items():
            canvas = FigureCanvasAgg(v)
            f = BytesIO()
            canvas.print_figure(f)
            f.seek(0)
            img = base64.b64encode(f.read()).decode()
            ret += (r'<img style="max-width:100%%;max-height:100%%;" '
                    r'src="data:image/png;base64,%s"><br>' % img)
        return ret
Ejemplo n.º 5
0
def mp(nx,
       ny,
       colorbar_size=2,
       size_x=None,
       size_y=None,
       ylabel_size=1.5,
       right_margin=0,
       xlabel_size=1,
       title_size=0.5,
       dpi=300,
       debug=0):
    """Make *nx* by *ny* plots of size *size_x* by *size_y*, that share common title, xlabel, ylabel, and colorbar. 
    ylabel is for the y axis, whose real estate comes out of the x dimension.  Vice-versa for x."""

    total_x = 1.0 * (nx * size_x + ylabel_size + colorbar_size + right_margin)
    total_y = 1.0 * (ny * size_y + xlabel_size + title_size)
    if size_x is None:
        size_x = 4
    if size_y is None:
        size_y = 4
    fr_x = size_x / total_x
    fr_y = size_y / total_y
    if debug > 0:
        print "Total", total_x, total_y, "pixels", total_x * dpi, total_y * dpi

    fig = matplotlib.figure.Figure((total_x, total_y), dpi=dpi)
    fig.set_canvas(FigureCanvasAgg(fig))
    axes_list = []
    counter = 0
    for j in range(ny - 1, -1, -1):
        counter += 1
        axes_list.append([])
        for i in range(nx):
            left = (ylabel_size + i * size_x) / total_x
            bottom = (xlabel_size + j * size_y) / total_y
            ax_extent = [left, bottom, size_x / total_x, size_y / total_y]
            ax = fig.add_axes(ax_extent)
            axes_list[-1].append(ax)
            if debug > 0:
                print "new ax: (l,b,r,t) (%f, %f, %f, %f)" % tuple(ax_extent)
                print "new axb: (x0,x1) (%f %f)" % (ax.bbox.x0, ax.bbox.x1)
    cbar = None
    if colorbar_size > 0:
        left = (ylabel_size + nx * size_x) / total_x
        bottom = 1.0 * xlabel_size / total_y
        cbar_extents = [
            left, bottom, (colorbar_size - ylabel_size) / total_x,
            ny * size_y / total_y
        ]
        if debug > 0:
            print cbar_extents
        cbar = fig.add_axes(cbar_extents)
    return fig, axes_list, cbar
Ejemplo n.º 6
0
    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 plot(self, fn=None, profile_field=None, profile_weight=None):
        """
        Save the current transfer function to a bitmap, or display
        it inline.

        Parameters
        ----------
        fn: string, optional
            Filename to save the image to. If None, the returns an image
            to an IPython session.

        Returns
        -------

        If fn is None, will return an image to an IPython notebook.

        """
        from yt.visualization._mpl_imports import FigureCanvasAgg
        from matplotlib.figure import Figure
        if self.tf is None:
            self.build_transfer_function()
            self.setup_default()
        tf = self.tf
        if self.log:
            xfunc = np.logspace
            xmi, xma = np.log10(self.bounds[0]), np.log10(self.bounds[1])
        else:
            xfunc = np.linspace
            # Need to strip units off of the bounds to avoid a recursion error
            # in matplotlib 1.3.1
            xmi, xma = [np.float64(b) for b in self.bounds]

        x = xfunc(xmi, xma, tf.nbins)
        y = tf.funcs[3].y
        w = np.append(x[1:] - x[:-1], x[-1] - x[-2])
        colors = np.array(
            [tf.funcs[0].y, tf.funcs[1].y, tf.funcs[2].y,
             np.ones_like(x)]).T

        fig = Figure(figsize=[6, 3])
        canvas = FigureCanvasAgg(fig)
        ax = fig.add_axes([0.2, 0.2, 0.75, 0.75])
        ax.bar(x,
               tf.funcs[3].y,
               w,
               edgecolor=[0.0, 0.0, 0.0, 0.0],
               log=self.log,
               color=colors,
               bottom=[0])

        if profile_field is not None:
            try:
                prof = self.profiles[self.field]
            except KeyError:
                self.setup_profile(profile_field, profile_weight)
                prof = self.profiles[self.field]
            try:
                prof[profile_field]
            except KeyError:
                prof.add_fields([profile_field])
            # Strip units, if any, for matplotlib 1.3.1
            xplot = np.array(prof.x)
            yplot = np.array(prof[profile_field] * tf.funcs[3].y.max() /
                             prof[profile_field].max())
            ax.plot(xplot, yplot, color='w', linewidth=3)
            ax.plot(xplot, yplot, color='k')

        ax.set_xscale({True: 'log', False: 'linear'}[self.log])
        ax.set_xlim(x.min(), x.max())
        ax.set_xlabel(self.ds._get_field_info(self.field).get_label())
        ax.set_ylabel(r'$\mathrm{alpha}$')
        ax.set_ylim(y.max() * 1.0e-3, y.max() * 2)

        if fn is None:
            from IPython.core.display import Image
            f = BytesIO()
            canvas.print_figure(f)
            f.seek(0)
            img = f.read()
            return Image(img)
        else:
            fig.savefig(fn)
    def plot(self, fn=None, profile_field=None, profile_weight=None):
        """
        Save the current transfer function to a bitmap, or display
        it inline.

        Parameters
        ----------
        fn: string, optional
            Filename to save the image to. If None, the returns an image
            to an IPython session.

        Returns
        -------

        If fn is None, will return an image to an IPython notebook.

        """
        if self.tf is None:
            self.build_transfer_function()
        tf = self.tf
        if self.log:
            xfunc = np.logspace
            xmi, xma = np.log10(self.bounds[0]), np.log10(self.bounds[1])
        else:
            xfunc = np.linspace
            # Need to strip units off of the bounds to avoid a recursion error
            # in matplotlib 1.3.1
            xmi, xma = [np.float64(b) for b in self.bounds]

        x = xfunc(xmi, xma, tf.nbins)
        y = tf.funcs[3].y
        w = np.append(x[1:] - x[:-1], x[-1] - x[-2])
        colors = np.array([tf.funcs[0].y, tf.funcs[1].y, tf.funcs[2].y, np.ones_like(x)]).T

        fig = Figure(figsize=[6, 3])
        canvas = FigureCanvasAgg(fig)
        ax = fig.add_axes([0.2, 0.2, 0.75, 0.75])
        ax.bar(x, tf.funcs[3].y, w, edgecolor=[0.0, 0.0, 0.0, 0.0], log=self.log, color=colors, bottom=[0])

        if profile_field is not None:
            try:
                prof = self.profiles[self.field]
            except KeyError:
                self.setup_profile(profile_field, profile_weight)
                prof = self.profiles[self.field]
            if profile_field not in prof.keys():
                prof.add_fields([profile_field], fractional=False, weight=profile_weight)
            # Strip units, if any, for matplotlib 1.3.1
            xplot = np.array(prof[self.field])
            yplot = np.array(prof[profile_field] * tf.funcs[3].y.max() / prof[profile_field].max())
            ax.plot(xplot, yplot, color="w", linewidth=3)
            ax.plot(xplot, yplot, color="k")

        ax.set_xscale({True: "log", False: "linear"}[self.log])
        ax.set_xlim(x.min(), x.max())
        ax.set_xlabel(self.ds._get_field_info(self.field).get_label())
        ax.set_ylabel(r"$\mathrm{alpha}$")
        ax.set_ylim(y.max() * 1.0e-3, y.max() * 2)

        if fn is None:
            from IPython.core.display import Image

            f = StringIO()
            canvas.print_figure(f)
            f.seek(0)
            img = f.read()
            return Image(img)
        else:
            fig.savefig(fn)
from yt.mods import *
import matplotlib
import pylab
from yt.visualization._mpl_imports import FigureCanvasAgg

#Figure parameters
total_width = 36
total_height = 6
n_plots = 4
fontsize = 30

fig = matplotlib.figure.Figure((total_width, total_height), dpi=300)
fig.set_canvas(FigureCanvasAgg(fig))

#numbers from this point on are relative to the total
m_left = 0.05  #left margin
m_right = 0.01
m_bottom = 0.2  #bottom margin
m_top = 0.05
width = (1. - m_right) / (n_plots) - m_left
height_main = (1 - m_bottom - m_top) * 0.66
height_dx = 1 - m_bottom - height_main - m_top
#ax_rho_d = fig.add_axes( [0.01, 0.01, 0.5, 0.5])
#ax_rho_1 = fig.add_axes( [m_left,m_bottom+height_dx, width, height_main])

ax_main = []
ax_diff = []
for n_plot in range(n_plots):
    this_plot_left = m_left + n_plot * (m_left + width)
    extents_density_diff = [this_plot_left, m_bottom, width, height_dx]
    extents_density_main = [