Beispiel #1
0
def req_mpl():
    try:
        _import_matplotlib()
    except (ImportError, ValueError):
        pytest.skip('Test requires matplotlib')
Beispiel #2
0
def matplotlib_scraper_multi(block, block_vars, gallery_conf, **kwargs):
    """Scrape Matplotlib images, but with both high and low-def...

    Parameters
    ----------
    block : tuple
        A tuple containing the (label, content, line_number) of the block.
    block_vars : dict
        Dict of block variables.
    gallery_conf : dict
        Contains the configuration of Sphinx-Gallery
    **kwargs : dict
        Additional keyword arguments to pass to
        :meth:`~matplotlib.figure.Figure.savefig`, e.g. ``format='svg'``.
        The ``format`` kwarg in particular is used to set the file extension
        of the output file (currently only 'png', 'jpg', and 'svg' are
        supported).

    Returns
    -------
    rst : str
        The ReSTructuredText that will be rendered to HTML containing
        the images. This is often produced by :func:`figure_rst`.
    """
    matplotlib, plt = scrapers._import_matplotlib()
    from matplotlib.animation import Animation
    image_path_iterator = block_vars['image_path_iterator']
    image_rsts = []
    # Check for animations
    anims = list()
    if gallery_conf.get('matplotlib_animations', False):
        for ani in block_vars['example_globals'].values():
            if isinstance(ani, Animation):
                anims.append(ani)
    # Then standard images
    for fig_num, image_path in zip(plt.get_fignums(), image_path_iterator):
        if 'format' in kwargs:
            image_path = '%s.%s' % (os.path.splitext(image_path)[0],
                                    kwargs['format'])
        # Set the fig_num figure as the current figure as we can't
        # save a figure that's not the current figure.
        fig = plt.figure(fig_num)
        # Deal with animations
        cont = False
        for anim in anims:
            if anim._fig is fig:
                image_rsts.append(_anim_rst(anim, image_path, gallery_conf))
                cont = True
                break
        if cont:
            continue
        # get fig titles
        fig_titles = scrapers._matplotlib_fig_titles(fig)
        to_rgba = matplotlib.colors.colorConverter.to_rgba
        # shallow copy should be fine here, just want to avoid changing
        # "kwargs" for subsequent figures processed by the loop
        these_kwargs = kwargs.copy()
        hikwargs = kwargs.copy()
        hikwargs['dpi'] = 200

        for attr in ['facecolor', 'edgecolor']:
            fig_attr = getattr(fig, 'get_' + attr)()
            default_attr = matplotlib.rcParams['figure.' + attr]
            if to_rgba(fig_attr) != to_rgba(default_attr) and \
                    attr not in kwargs:
                these_kwargs[attr] = fig_attr
        try:
            hipath = image_path[:-4] + '_hidpi' + image_path[-4:]
            fig.savefig(hipath, **hikwargs)
            fig.savefig(image_path, **these_kwargs)

        except Exception:
            plt.close('all')
            raise
        if 'images' in gallery_conf['compress_images']:
            optipng(image_path, gallery_conf['compress_images_args'])
        image_rsts.append(
            figure_rst([image_path], gallery_conf['src_dir'], fig_titles))
    plt.close('all')
    rst = ''
    if len(image_rsts) == 1:
        rst = image_rsts[0]
    elif len(image_rsts) > 1:
        image_rsts = [
            re.sub(r':class: sphx-glr-single-img',
                   ':class: sphx-glr-multi-img', image) for image in image_rsts
        ]
        image_rsts = [
            HLIST_IMAGE_MATPLOTLIB + indent(image, u' ' * 6)
            for image in image_rsts
        ]
        rst = HLIST_HEADER + ''.join(image_rsts)
    return rst