Python matplotlib.rcParams() Examples

The following are 30 code examples of matplotlib.rcParams(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib , or try the search function .
Example #1
Source File: texmanager.py    From Computable with MIT License 6 votes vote down vote up
def get_font_config(self):
        """Reinitializes self if relevant rcParams on have changed."""
        if self._rc_cache is None:
            self._rc_cache = dict([(k, None) for k in self._rc_cache_keys])
        changed = [par for par in self._rc_cache_keys
                   if rcParams[par] != self._rc_cache[par]]
        if changed:
            if DEBUG:
                print('DEBUG following keys changed:', changed)
            for k in changed:
                if DEBUG:
                    print('DEBUG %-20s: %-10s -> %-10s' %
                          (k, self._rc_cache[k], rcParams[k]))
                # deepcopy may not be necessary, but feels more future-proof
                self._rc_cache[k] = copy.deepcopy(rcParams[k])
            if DEBUG:
                print('DEBUG RE-INIT\nold fontconfig:', self._fontconfig)
            self.__init__()
        if DEBUG:
            print('DEBUG fontconfig:', self._fontconfig)
        return self._fontconfig 
Example #2
Source File: tools.py    From mplhep with MIT License 6 votes vote down vote up
def hardcopy_fonts():
    path = os.path.abspath(__file__)
    pkg_dir = "/" + "/".join(path.split("/")[:-1])
    os.system(
        "cp -r {}/fonts/firasans/* ".format(pkg_dir)
        + os.path.join(mpl.rcParams["datapath"] + "/fonts/ttf/")
    )
    os.system(
        "cp -r {}/fonts/firamath/* ".format(pkg_dir)
        + os.path.join(mpl.rcParams["datapath"] + "/fonts/ttf/")
    )
    os.system(
        "cp -r {}/fonts/texgyreheros/* ".format(pkg_dir)
        + os.path.join(mpl.rcParams["datapath"] + "/fonts/ttf/")
    )
    os.system("rm " + os.path.join(mpl.get_cachedir() + "/font*")) 
Example #3
Source File: scrapers.py    From sphinx-gallery with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _anim_rst(anim, image_path, gallery_conf):
    from matplotlib.animation import ImageMagickWriter
    # output the thumbnail as the image, as it will just be copied
    # if it's the file thumbnail
    fig = anim._fig
    image_path = image_path.replace('.png', '.gif')
    fig_size = fig.get_size_inches()
    thumb_size = gallery_conf['thumbnail_size']
    use_dpi = round(
        min(t_s / f_s for t_s, f_s in zip(thumb_size, fig_size)))
    # FFmpeg is buggy for GIFs
    if ImageMagickWriter.isAvailable():
        writer = 'imagemagick'
    else:
        writer = None
    anim.save(image_path, writer=writer, dpi=use_dpi)
    html = anim._repr_html_()
    if html is None:  # plt.rcParams['animation.html'] == 'none'
        html = anim.to_jshtml()
    html = indent(html, '         ')
    return _ANIMATION_RST.format(html) 
Example #4
Source File: texmanager.py    From Computable with MIT License 6 votes vote down vote up
def get_rgba(self, tex, fontsize=None, dpi=None, rgb=(0, 0, 0)):
        """
        Returns latex's rendering of the tex string as an rgba array
        """
        if not fontsize:
            fontsize = rcParams['font.size']
        if not dpi:
            dpi = rcParams['savefig.dpi']
        r, g, b = rgb
        key = tex, self.get_font_config(), fontsize, dpi, tuple(rgb)
        Z = self.rgba_arrayd.get(key)

        if Z is None:
            alpha = self.get_grey(tex, fontsize, dpi)

            Z = np.zeros((alpha.shape[0], alpha.shape[1], 4), np.float)

            Z[:, :, 0] = r
            Z[:, :, 1] = g
            Z[:, :, 2] = b
            Z[:, :, 3] = alpha
            self.rgba_arrayd[key] = Z

        return Z 
Example #5
Source File: gridspec.py    From Computable with MIT License 6 votes vote down vote up
def __init__(self, nrows, ncols,
                 subplot_spec,
                 wspace=None, hspace=None,
                 height_ratios=None, width_ratios=None):
        """
        The number of rows and number of columns of the grid need to
        be set. An instance of SubplotSpec is also needed to be set
        from which the layout parameters will be inherited. The wspace
        and hspace of the layout can be optionally specified or the
        default values (from the figure or rcParams) will be used.
        """
        self._wspace=wspace
        self._hspace=hspace

        self._subplot_spec = subplot_spec

        GridSpecBase.__init__(self, nrows, ncols,
                              width_ratios=width_ratios,
                              height_ratios=height_ratios) 
Example #6
Source File: font_manager.py    From Computable with MIT License 6 votes vote down vote up
def set_weight(self, weight):
        """
        Set the font weight.  May be either a numeric value in the
        range 0-1000 or one of 'ultralight', 'light', 'normal',
        'regular', 'book', 'medium', 'roman', 'semibold', 'demibold',
        'demi', 'bold', 'heavy', 'extra bold', 'black'
        """
        if weight is None:
            weight = rcParams['font.weight']
        try:
            weight = int(weight)
            if weight < 0 or weight > 1000:
                raise ValueError()
        except ValueError:
            if weight not in weight_dict:
                raise ValueError("weight is invalid")
        self._weight = weight 
Example #7
Source File: font_manager.py    From Computable with MIT License 6 votes vote down vote up
def set_stretch(self, stretch):
        """
        Set the font stretch or width.  Options are: 'ultra-condensed',
        'extra-condensed', 'condensed', 'semi-condensed', 'normal',
        'semi-expanded', 'expanded', 'extra-expanded' or
        'ultra-expanded', or a numeric value in the range 0-1000.
        """
        if stretch is None:
            stretch = rcParams['font.stretch']
        try:
            stretch = int(stretch)
            if stretch < 0 or stretch > 1000:
                raise ValueError()
        except ValueError:
            if stretch not in stretch_dict:
                raise ValueError("stretch is invalid")
        self._stretch = stretch 
Example #8
Source File: gridspec.py    From Computable with MIT License 6 votes vote down vote up
def get_subplot_params(self, fig=None):
        """
        return a dictionary of subplot layout parameters. The default
        parameters are from rcParams unless a figure attribute is set.
        """
        from matplotlib.figure import SubplotParams
        import copy
        if fig is None:
            kw = dict([(k, rcParams["figure.subplot."+k]) \
                       for k in self._AllowedKeys])
            subplotpars = SubplotParams(**kw)
        else:
            subplotpars = copy.copy(fig.subplotpars)

        update_kw = dict([(k, getattr(self, k)) for k in self._AllowedKeys])
        subplotpars.update(**update_kw)

        return subplotpars 
Example #9
Source File: ticker.py    From Computable with MIT License 6 votes vote down vote up
def __init__(self, useOffset=True, useMathText=None, useLocale=None):
        # useOffset allows plotting small data ranges with large offsets: for
        # example: [1+1e-9,1+2e-9,1+3e-9] useMathText will render the offset
        # and scientific notation in mathtext

        self.set_useOffset(useOffset)
        self._usetex = rcParams['text.usetex']
        if useMathText is None:
            useMathText = rcParams['axes.formatter.use_mathtext']
        self._useMathText = useMathText
        self.orderOfMagnitude = 0
        self.format = ''
        self._scientific = True
        self._powerlimits = rcParams['axes.formatter.limits']
        if useLocale is None:
            useLocale = rcParams['axes.formatter.use_locale']
        self._useLocale = useLocale 
Example #10
Source File: collections.py    From Computable with MIT License 6 votes vote down vote up
def set_facecolor(self, c):
        """
        Set the facecolor(s) of the collection.  *c* can be a
        matplotlib color arg (all patches have same color), or a
        sequence of rgba tuples; if it is a sequence the patches will
        cycle through the sequence.

        If *c* is 'none', the patch will not be filled.

        ACCEPTS: matplotlib color arg or sequence of rgba tuples
        """
        self._is_filled = True
        try:
            if c.lower() == 'none':
                self._is_filled = False
        except AttributeError:
            pass
        if c is None:
            c = mpl.rcParams['patch.facecolor']
        self._facecolors_original = c
        self._facecolors = mcolors.colorConverter.to_rgba_array(c, self._alpha) 
Example #11
Source File: mathmpl.py    From Computable with MIT License 6 votes vote down vote up
def latex2png(latex, filename, fontset='cm'):
    latex = "$%s$" % latex
    orig_fontset = rcParams['mathtext.fontset']
    rcParams['mathtext.fontset'] = fontset
    if os.path.exists(filename):
        depth = mathtext_parser.get_depth(latex, dpi=100)
    else:
        try:
            depth = mathtext_parser.to_png(filename, latex, dpi=100)
        except:
            warnings.warn("Could not render math expression %s" % latex,
                          Warning)
            depth = 0
    rcParams['mathtext.fontset'] = orig_fontset
    sys.stdout.write("#")
    sys.stdout.flush()
    return depth

# LaTeX to HTML translation stuff: 
Example #12
Source File: geo.py    From Computable with MIT License 6 votes vote down vote up
def cla(self):
        Axes.cla(self)

        self.set_longitude_grid(30)
        self.set_latitude_grid(15)
        self.set_longitude_grid_ends(75)
        self.xaxis.set_minor_locator(NullLocator())
        self.yaxis.set_minor_locator(NullLocator())
        self.xaxis.set_ticks_position('none')
        self.yaxis.set_ticks_position('none')
        self.yaxis.set_tick_params(label1On=True)
        # Why do we need to turn on yaxis tick labels, but
        # xaxis tick labels are already on?

        self.grid(rcParams['axes.grid'])

        Axes.set_xlim(self, -np.pi, np.pi)
        Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0) 
Example #13
Source File: polar.py    From Computable with MIT License 6 votes vote down vote up
def cla(self):
        Axes.cla(self)

        self.title.set_y(1.05)

        self.xaxis.set_major_formatter(self.ThetaFormatter())
        self.xaxis.isDefault_majfmt = True
        angles = np.arange(0.0, 360.0, 45.0)
        self.set_thetagrids(angles)
        self.yaxis.set_major_locator(self.RadialLocator(self.yaxis.get_major_locator()))

        self.grid(rcParams['polaraxes.grid'])
        self.xaxis.set_ticks_position('none')
        self.yaxis.set_ticks_position('none')
        self.yaxis.set_tick_params(label1On=True)
        # Why do we need to turn on yaxis tick labels, but
        # xaxis tick labels are already on?

        self.set_theta_offset(self._default_theta_offset)
        self.set_theta_direction(self._default_theta_direction) 
Example #14
Source File: text.py    From Computable with MIT License 6 votes vote down vote up
def is_math_text(s):
        """
        Returns a cleaned string and a boolean flag.
        The flag indicates if the given string *s* contains any mathtext,
        determined by counting unescaped dollar signs. If no mathtext
        is present, the cleaned string has its dollar signs unescaped.
        If usetex is on, the flag always has the value "TeX".
        """
        # Did we find an even number of non-escaped dollar signs?
        # If so, treat is as math text.
        if rcParams['text.usetex']:
            if s == ' ':
                s = r'\ '
            return s, 'TeX'

        if cbook.is_math_text(s):
            return s, True
        else:
            return s.replace(r'\$', '$'), False 
Example #15
Source File: polar.py    From Computable with MIT License 5 votes vote down vote up
def __call__(self, x, pos=None):
        # \u00b0 : degree symbol
        if rcParams['text.usetex'] and not rcParams['text.latex.unicode']:
            return r"$%0.0f^\circ$" % ((x / np.pi) * 180.0)
        else:
            # we use unicode, rather than mathtext with \circ, so
            # that it will work correctly with any arbitrary font
            # (assuming it has a degree sign), whereas $5\circ$
            # will only work correctly with one of the supported
            # math fonts (Computer Modern and STIX)
            return u"%0.0f\u00b0" % ((x / np.pi) * 180.0) 
Example #16
Source File: geo.py    From Computable with MIT License 5 votes vote down vote up
def __call__(self, x, pos=None):
            degrees = (x / np.pi) * 180.0
            degrees = round(degrees / self._round_to) * self._round_to
            if rcParams['text.usetex'] and not rcParams['text.latex.unicode']:
                return r"$%0.0f^\circ$" % degrees
            else:
                return u"%0.0f\u00b0" % degrees 
Example #17
Source File: font_manager.py    From Computable with MIT License 5 votes vote down vote up
def get_default_size():
        """
        Return the default font size.
        """
        return rcParams['font.size'] 
Example #18
Source File: ticker.py    From Computable with MIT License 5 votes vote down vote up
def set_useLocale(self, val):
        if val is None:
            self._useLocale = rcParams['axes.formatter.use_locale']
        else:
            self._useLocale = val 
Example #19
Source File: font_manager.py    From Computable with MIT License 5 votes vote down vote up
def score_family(self, families, family2):
        """
        Returns a match score between the list of font families in
        *families* and the font family name *family2*.

        An exact match anywhere in the list returns 0.0.

        A match by generic font name will return 0.1.

        No match will return 1.0.
        """
        if not isinstance(families, (list, tuple)):
            families = [families]
        family2 = family2.lower()
        for i, family1 in enumerate(families):
            family1 = family1.lower()
            if family1 in font_family_aliases:
                if family1 in ('sans', 'sans serif'):
                    family1 = 'sans-serif'
                options = rcParams['font.' + family1]
                options = [x.lower() for x in options]
                if family2 in options:
                    idx = options.index(family2)
                    return ((0.1 * (float(idx) / len(options))) *
                            (float(i) / float(len(families))))
            elif family1 == family2:
                # The score should be weighted by where in the
                # list the font was found.
                return float(i) / float(len(families))
        return 1.0 
Example #20
Source File: ticker.py    From Computable with MIT License 5 votes vote down vote up
def fix_minus(self, s):
        """use a unicode minus rather than hyphen"""
        if rcParams['text.usetex'] or not rcParams['axes.unicode_minus']:
            return s
        else:
            return s.replace('-', u'\u2212') 
Example #21
Source File: offsetbox.py    From Computable with MIT License 5 votes vote down vote up
def set_fontsize(self, s=None):
        """
        set fontsize in points
        """
        if s is None:
            s = rcParams["legend.fontsize"]

        self.prop = FontProperties(size=s) 
Example #22
Source File: font_manager.py    From Computable with MIT License 5 votes vote down vote up
def get_variant(self):
        """
        Return the font variant.  Values are: 'normal' or
        'small-caps'.
        """
        if self._variant is None:
            return rcParams['font.variant']
        return self._variant 
Example #23
Source File: font_manager.py    From Computable with MIT License 5 votes vote down vote up
def get_style(self):
        """
        Return the font style.  Values are: 'normal', 'italic' or
        'oblique'.
        """
        if self._slant is None:
            return rcParams['font.style']
        return self._slant 
Example #24
Source File: gridspec.py    From Computable with MIT License 5 votes vote down vote up
def get_subplot_params(self, fig=None):
        """
        return a dictionary of subplot layout parameters.
        """

        if fig is None:
            hspace = rcParams["figure.subplot.hspace"]
            wspace = rcParams["figure.subplot.wspace"]
        else:
            hspace = fig.subplotpars.hspace
            wspace = fig.subplotpars.wspace

        if self._hspace is not None:
            hspace = self._hspace

        if self._wspace is not None:
            wspace = self._wspace

        figbox = self._subplot_spec.get_position(fig, return_all=False)

        left, bottom, right, top = figbox.extents

        from matplotlib.figure import SubplotParams
        sp = SubplotParams(left=left,
                           right=right,
                           bottom=bottom,
                           top=top,
                           wspace=wspace,
                           hspace=hspace)

        return sp 
Example #25
Source File: axis.py    From Computable with MIT License 5 votes vote down vote up
def _get_offset_text(self):
        # x in axes coords, y in display coords (to be updated at draw time)
        offsetText = mtext.Text(x=1, y=0,
            fontproperties=font_manager.FontProperties(
                                          size=rcParams['xtick.labelsize']),
            color=rcParams['xtick.color'],
            verticalalignment='top',
            horizontalalignment='right',
            )
        offsetText.set_transform(mtransforms.blended_transform_factory(
                self.axes.transAxes, mtransforms.IdentityTransform()))
        self._set_artist_props(offsetText)
        self.offset_text_position = 'bottom'
        return offsetText 
Example #26
Source File: patches.py    From Computable with MIT License 5 votes vote down vote up
def set_antialiased(self, aa):
        """
        Set whether to use antialiased rendering

        ACCEPTS: [True | False]  or None for default
        """
        if aa is None:
            aa = mpl.rcParams['patch.antialiased']
        self._antialiased = aa 
Example #27
Source File: backend_bases.py    From Computable with MIT License 5 votes vote down vote up
def get_default_filetype(self):
        """
        Get the default savefig file format as specified in rcParam
        ``savefig.format``. Returned string excludes period. Overridden
        in backends that only support a single file type.
        """
        return rcParams['savefig.format'] 
Example #28
Source File: texmanager.py    From Computable with MIT License 5 votes vote down vote up
def get_custom_preamble(self):
        """returns a string containing user additions to the tex preamble"""
        return '\n'.join(rcParams['text.latex.preamble']) 
Example #29
Source File: patches.py    From Computable with MIT License 5 votes vote down vote up
def set_edgecolor(self, color):
        """
        Set the patch edge color

        ACCEPTS: mpl color spec, or None for default, or 'none' for no color
        """
        if color is None:
            color = mpl.rcParams['patch.edgecolor']
        self._original_edgecolor = color
        self._edgecolor = colors.colorConverter.to_rgba(color, self._alpha) 
Example #30
Source File: patches.py    From Computable with MIT License 5 votes vote down vote up
def set_facecolor(self, color):
        """
        Set the patch face color

        ACCEPTS: mpl color spec, or None for default, or 'none' for no color
        """
        if color is None:
            color = mpl.rcParams['patch.facecolor']
        self._original_facecolor = color  # save: otherwise changing _fill
                                          # may lose alpha information
        self._facecolor = colors.colorConverter.to_rgba(color, self._alpha)
        if not self._fill:
            self._facecolor = list(self._facecolor)
            self._facecolor[3] = 0