Python matplotlib.rcParams() Examples

The following are 30 code examples for showing how to use matplotlib.rcParams(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module matplotlib , or try the search function .

Example 1
Project: OpenTrader   Author: OpenTrading   File: OTBackTest.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def vPlotEquityCurves(oBt, mOhlc, oChefModule,
                      sPeriod='W',
                      close_label='C',):
    import matplotlib
    import matplotlib.pylab as pylab
    # FixMe:
    matplotlib.rcParams['figure.figsize'] = (10, 5)

    # FixMe: derive the period from the sTimeFrame
    oChefModule.vPlotEquity(oBt.equity, mOhlc, sTitle="%s\nEquity" % repr(oBt),
                            sPeriod=sPeriod,
                            close_label=close_label,
                            )
    pylab.show()

    oBt.vPlotTrades()
    pylab.legend(loc='lower left')
    pylab.show()

    ## oBt.vPlotTrades(subset=slice(sYear+'-05-01', sYear+'-09-01'))
    ## pylab.legend(loc='lower left')
    ## pylab.show() 
Example 2
Project: mplhep   Author: scikit-hep   File: tools.py    License: 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
Project: sphinx-gallery   Author: sphinx-gallery   File: scrapers.py    License: 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
Project: Computable   Author: ktraunmueller   File: axis.py    License: MIT License 6 votes vote down vote up
def _get_label(self):
        # x in axes coords, y in display coords (to be updated at draw
        # time by _update_label_positions)
        label = mtext.Text(x=0.5, y=0,
            fontproperties=font_manager.FontProperties(
                               size=rcParams['axes.labelsize'],
                               weight=rcParams['axes.labelweight']),
            color=rcParams['axes.labelcolor'],
            verticalalignment='top',
            horizontalalignment='center',
            )

        label.set_transform(mtransforms.blended_transform_factory(
            self.axes.transAxes, mtransforms.IdentityTransform()))

        self._set_artist_props(label)
        self.label_position = 'bottom'
        return label 
Example 5
Project: Computable   Author: ktraunmueller   File: axis.py    License: MIT License 6 votes vote down vote up
def _get_label(self):
        # x in display coords (updated by _update_label_position)
        # y in axes coords
        label = mtext.Text(x=0, y=0.5,
            # todo: get the label position
            fontproperties=font_manager.FontProperties(
                               size=rcParams['axes.labelsize'],
                               weight=rcParams['axes.labelweight']),
            color=rcParams['axes.labelcolor'],
            verticalalignment='bottom',
            horizontalalignment='center',
            rotation='vertical',
            rotation_mode='anchor',
            )
        label.set_transform(mtransforms.blended_transform_factory(
            mtransforms.IdentityTransform(), self.axes.transAxes))

        self._set_artist_props(label)
        self.label_position = 'left'
        return label 
Example 6
Project: Computable   Author: ktraunmueller   File: gridspec.py    License: 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 7
Project: Computable   Author: ktraunmueller   File: gridspec.py    License: 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 8
Project: Computable   Author: ktraunmueller   File: font_manager.py    License: 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 9
Project: Computable   Author: ktraunmueller   File: font_manager.py    License: 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 10
Project: Computable   Author: ktraunmueller   File: ticker.py    License: 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 11
Project: Computable   Author: ktraunmueller   File: mathmpl.py    License: 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
Project: Computable   Author: ktraunmueller   File: geo.py    License: 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
Project: Computable   Author: ktraunmueller   File: polar.py    License: 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
Project: Computable   Author: ktraunmueller   File: text.py    License: 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
Project: Computable   Author: ktraunmueller   File: texmanager.py    License: 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 16
Project: Computable   Author: ktraunmueller   File: texmanager.py    License: 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 17
Project: Computable   Author: ktraunmueller   File: collections.py    License: 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 18
Project: NanoPlot   Author: wdecoster   File: nanoplotter_main.py    License: GNU General Public License v3.0 5 votes vote down vote up
def plot_settings(plot_settings, dpi):
    sns.set(**plot_settings)
    mpl.rcParams['savefig.dpi'] = dpi 
Example 19
Project: connecting_the_dots   Author: autonomousvision   File: plt.py    License: MIT License 5 votes vote down vote up
def non_annoying_pause(interval, focus_figure=False):
  # https://github.com/matplotlib/matplotlib/issues/11131
  backend = mpl.rcParams['backend']
  if backend in _interactive_bk:
    figManager = _pylab_helpers.Gcf.get_active()
    if figManager is not None:
      canvas = figManager.canvas
      if canvas.figure.stale:
        canvas.draw()
      if focus_figure:
        plt.show(block=False)
      canvas.start_event_loop(interval)
      return
  time.sleep(interval) 
Example 20
Project: PyMICAPS   Author: flashlxy   File: Map.py    License: GNU General Public License v2.0 5 votes vote down vote up
def DrawContourAndMark(contour, x, y, z, level, clipborder, patch, m):

        # 是否绘制等值线 ------ 等值线和标注是一体的

        if contour.contour['visible']:

            matplotlib.rcParams['contour.negative_linestyle'] = 'dashed'
            if contour.contour['colorline']:
                CS1 = m.contour(x, y, z, levels=level, linewidths=contour.contour['linewidth'])
            else:
                CS1 = m.contour(x,
                                y,
                                z,
                                levels=level,
                                linewidths=contour.contour['linewidth'],
                                colors=contour.contour['linecolor'])

            # 是否绘制等值线标注
            CS2 = None
            if contour.contourlabel['visible']:
                CS2 = plt.clabel(CS1,
                                 inline=1,
                                 fmt=contour.contourlabel['fmt'],
                                 inline_spacing=contour.contourlabel['inlinespacing'],
                                 fontsize=contour.contourlabel['fontsize'],
                                 colors=contour.contourlabel['fontcolor'])

            # 用区域边界裁切等值线图
            if clipborder.path is not None and clipborder.using:
                for collection in CS1.collections:
                    # collection.set_clip_on(True)
                    collection.set_clip_path(patch)

                if CS2 is not None:
                    for text in CS2:
                        if not clipborder.path.contains_point(text.get_position()):
                            text.remove() 
Example 21
Project: garden.matplotlib   Author: kivy-garden   File: backend_kivy.py    License: MIT License 5 votes vote down vote up
def _init_toolbar(self):
        '''A Toolbar is created with an ActionBar widget in which buttons are
           added with a specific behavior given by a callback. The buttons
           properties are given by matplotlib.
        '''
        basedir = os.path.join(rcParams['datapath'], 'images')
        actionview = ActionView()
        actionprevious = ActionPrevious(title="Navigation", with_previous=False)
        actionoverflow = ActionOverflow()
        actionview.add_widget(actionprevious)
        actionview.add_widget(actionoverflow)
        actionview.use_separator = True
        self.actionbar.add_widget(actionview)
        id_group = uuid.uuid4()
        for text, tooltip_text, image_file, callback in self.toolitems:
            if text is None:
                actionview.add_widget(ActionSeparator())
                continue
            fname = os.path.join(basedir, image_file + '.png')
            if text in ['Pan', 'Zoom']:
                action_button = ActionToggleButton(text=text, icon=fname,
                                                   group=id_group)
            else:
                action_button = ActionButton(text=text, icon=fname)
            action_button.bind(on_press=getattr(self, callback))
            actionview.add_widget(action_button) 
Example 22
Project: garden.matplotlib   Author: kivy-garden   File: backend_kivy.py    License: MIT License 5 votes vote down vote up
def _get_toolbar(self):
        if rcParams['toolbar'] == 'toolbar2':
            toolbar = NavigationToolbar2Kivy(self.canvas)
        else:
            toolbar = None
        return toolbar 
Example 23
Project: recruit   Author: Frank-qlu   File: test_series.py    License: Apache License 2.0 5 votes vote down vote up
def test_dont_modify_rcParams(self):
        # GH 8242
        key = 'axes.prop_cycle'
        colors = self.plt.rcParams[key]
        _, ax = self.plt.subplots()
        Series([1, 2, 3]).plot(ax=ax)
        assert colors == self.plt.rcParams[key] 
Example 24
Project: recruit   Author: Frank-qlu   File: test_series.py    License: Apache License 2.0 5 votes vote down vote up
def test_series_grid_settings(self):
        # Make sure plot defaults to rcParams['axes.grid'] setting, GH 9792
        self._check_grid_settings(Series([1, 2, 3]),
                                  plotting._core._series_kinds +
                                  plotting._core._common_kinds) 
Example 25
Project: recruit   Author: Frank-qlu   File: test_series.py    License: Apache License 2.0 5 votes vote down vote up
def test_time_series_plot_color_with_empty_kwargs(self):
        import matplotlib as mpl

        def_colors = self._unpack_cycler(mpl.rcParams)
        index = date_range('1/1/2000', periods=12)
        s = Series(np.arange(1, 13), index=index)

        ncolors = 3

        _, ax = self.plt.subplots()
        for i in range(ncolors):
            ax = s.plot(ax=ax)
        self._check_colors(ax.get_lines(), linecolors=def_colors[:ncolors]) 
Example 26
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_MOverNPlotting.py    License: MIT License 5 votes vote down vote up
def makefigure(size_format = "EPSL", aspect_ratio=16./9.):
    """
    This function makes a figure object based on the specified size_format
    of specific journals. This could be implemented at a global level.
    Sets RC params for figures

    MDH

    """

    # Set up fonts for plots
    label_size = 10
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['Liberation Sans']
    rcParams['font.size'] = label_size
    rcParams['text.usetex'] = False

    # make the figure
    if type(size_format) is float:
        fig = plt.figure(1, facecolor='white',figsize=(size_format,size_format/aspect_ratio))
    elif size_format == "geomorphology":
        fig = plt.figure(1, facecolor='white',figsize=(6.25,6.25/aspect_ratio))
    elif size_format == "big":
        fig = plt.figure(1, facecolor='white',figsize=(16,16./aspect_ratio))
    elif size_format == "EPSL":
        fig = plt.figure(1, facecolor='white',figsize=(7.48,7.48/aspect_ratio))
    else:
        fig = plt.figure(1, facecolor='white',figsize=(4.92126,4.92126/aspect_ratio))

    return fig

#=============================================================================
#=============================================================================
# ANALYSIS FUNCTIONS
# These functions analyse the data (for example, doing the outlier checking)
#============================================================================= 
Example 27
Project: easyplot   Author: HamsterHuey   File: easyplot.py    License: MIT License 5 votes vote down vote up
def set_fontsize(self, font_size):
        """ Updates global font size for all plot elements"""
        mpl.rcParams['font.size'] = font_size
        self.redraw()
        #TODO: Implement individual font size setting
#        params = {'font.family': 'serif',
#          'font.size': 16,
#          'axes.labelsize': 18,
#          'text.fontsize': 18,
#          'legend.fontsize': 18,
#          'xtick.labelsize': 18,
#          'ytick.labelsize': 18,
#          'text.usetex': True}
#        mpl.rcParams.update(params)
    
#    def set_font(self, family=None, weight=None, size=None):
#        """ Updates global font properties for all plot elements
#        
#        TODO: Font family and weight don't update dynamically"""
#        if family is None:
#            family = mpl.rcParams['font.family']
#        if weight is None:
#            weight = mpl.rcParams['font.weight']
#        if size is None:
#            size = mpl.rcParams['font.size']
#        mpl.rc('font', family=family, weight=weight, size=size)
#        self.redraw() 
Example 28
Project: kevlar   Author: kevlar-dev   File: dist.py    License: MIT License 5 votes vote down vote up
def main(args):
    mask = khmer.Nodetable.load(args.mask)
    mu, sigma, data = dist(
        args.infiles, mask, ksize=args.ksize, memory=args.memory,
        threads=args.threads,
    )
    out = {'mu': mu, 'sigma': sigma}
    print(json.dumps(out))

    if args.tsv:
        data.to_csv(args.tsv, sep='\t', index=False)

    if args.plot:
        import os
        try:  # pragma: no cover
            import matplotlib
            if os.environ.get('DISPLAY', '') == '':
                matplotlib.use('Agg')
            from matplotlib import pyplot as plt
        except RuntimeError as rerr:  # pragma: no cover
            if 'Python is not installed as a framework' not in str(rerr):
                raise rerr
            message = 'There was a problem loading matplotlib. '
            message += 'Try https://stackoverflow.com/q/21784641/459780 '
            message += 'for troubleshooting ideas.'
            raise RuntimeError(message)
        matplotlib.rcParams["figure.figsize"] = [12, 6]
        matplotlib.rcParams['axes.labelsize'] = 16
        matplotlib.rcParams['xtick.labelsize'] = 16
        plt.plot(data['Abundance'], data['Count'], color='blue')
        plt.axvline(x=mu, color='blue', linestyle='--')
        plt.axvline(x=mu - sigma, color='red', linestyle=':')
        plt.axvline(x=mu + sigma, color='red', linestyle=':')
        plt.xlim(args.plot_xlim)
        plt.xlabel('K-mer abundance')
        plt.ylabel('Frequency')
        plt.savefig(args.plot, dpi=300) 
Example 29
Project: calfem-python   Author: CALFEM   File: vis_mpl.py    License: MIT License 5 votes vote down vote up
def set_figure_dpi(dpi):
    mpl.rcParams['figure.dpi'] = dpi 
Example 30
Project: vnpy_crypto   Author: birforce   File: plotting.py    License: MIT License 5 votes vote down vote up
def set_fontsize(self, size):
        import matplotlib as mpl
        old_size = mpl.rcParams['font.size']
        mpl.rcParams['font.size'] = size

        def revert():
            mpl.rcParams['font.size'] = old_size

        self._inverse_actions.append(revert)

#-------------------------------------------------------------------------------
# Plotting functions