Python matplotlib.rc_params_from_file() Examples

The following are 24 code examples of matplotlib.rc_params_from_file(). 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: core.py    From neural-network-animation with MIT License 6 votes vote down vote up
def use(name):
    """Use matplotlib style settings from a known style sheet or from a file.

    Parameters
    ----------
    name : str or list of str
        Name of style or path/URL to a style file. For a list of available
        style names, see `style.available`. If given a list, each style is
        applied from first to last in the list.
    """
    if cbook.is_string_like(name):
        name = [name]

    for style in name:
        if style in library:
            mpl.rcParams.update(library[style])
        else:
            try:
                rc = rc_params_from_file(style, use_default_template=False)
                mpl.rcParams.update(rc)
            except:
                msg = ("'%s' not found in the style library and input is "
                       "not a valid URL or path. See `style.available` for "
                       "list of available styles.")
                raise ValueError(msg % style) 
Example #2
Source File: __init__.py    From holoviews with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_style(key):
    """
    Select a style by name, e.g. set_style('default'). To revert to the
    previous style use the key 'unset' or False.
    """
    if key is None:
        return
    elif not key or key in ['unset', 'backup']:
        if 'backup' in styles:
            plt.rcParams.update(styles['backup'])
        else:
            raise Exception('No style backed up to restore')
    elif key not in styles:
        raise KeyError('%r not in available styles.')
    else:
        path = os.path.join(os.path.dirname(__file__), styles[key])
        new_style = rc_params_from_file(path, use_default_template=False)
        styles['backup'] = dict(plt.rcParams)

        plt.rcParams.update(new_style)


# Define matplotlib based style cycles and Palettes 
Example #3
Source File: core.py    From ImageFusion with MIT License 6 votes vote down vote up
def use(name):
    """Use matplotlib style settings from a known style sheet or from a file.

    Parameters
    ----------
    name : str or list of str
        Name of style or path/URL to a style file. For a list of available
        style names, see `style.available`. If given a list, each style is
        applied from first to last in the list.
    """
    if cbook.is_string_like(name):
        name = [name]

    for style in name:
        if style in library:
            mpl.rcParams.update(library[style])
        else:
            try:
                rc = rc_params_from_file(style, use_default_template=False)
                mpl.rcParams.update(rc)
            except:
                msg = ("'%s' not found in the style library and input is "
                       "not a valid URL or path. See `style.available` for "
                       "list of available styles.")
                raise ValueError(msg % style) 
Example #4
Source File: core.py    From ImageFusion with MIT License 5 votes vote down vote up
def read_style_directory(style_dir):
    """Return dictionary of styles defined in `style_dir`."""
    styles = dict()
    for path, name in iter_style_files(style_dir):
        styles[name] = rc_params_from_file(path, use_default_template=False)
    return styles 
Example #5
Source File: test_rcparams.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_if_rctemplate_would_be_valid(tmpdir):
    # This tests if the matplotlibrc.template file would result in a valid
    # rc file if all lines are uncommented.
    path_to_rc = os.path.join(mpl.get_data_path(), 'matplotlibrc')
    with open(path_to_rc, "r") as f:
        rclines = f.readlines()
    newlines = []
    for line in rclines:
        if line[0] == "#":
            newline = line[1:]
        else:
            newline = line
        if "$TEMPLATE_BACKEND" in newline:
            newline = "backend : Agg"
        if "datapath" in newline:
            newline = ""
        newlines.append(newline)
    d = tmpdir.mkdir('test1')
    fname = str(d.join('testrcvalid.temp'))
    with open(fname, "w") as f:
        f.writelines(newlines)
    with pytest.warns(None) as record:
        mpl.rc_params_from_file(fname,
                                fail_on_error=True,
                                use_default_template=False)
        assert len(record) == 0 
Example #6
Source File: test_rcparams.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_Issue_1713():
    utf32_be = os.path.join(os.path.dirname(__file__),
                           'test_utf32_be_rcparams.rc')
    import locale
    with mock.patch('locale.getpreferredencoding', return_value='UTF-32-BE'):
        rc = mpl.rc_params_from_file(utf32_be, True, False)
    assert rc.get('timezone') == 'UTC' 
Example #7
Source File: core.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def read_style_directory(style_dir):
    """Return dictionary of styles defined in `style_dir`."""
    styles = dict()
    for path, name in iter_style_files(style_dir):
        with warnings.catch_warnings(record=True) as warns:
            styles[name] = rc_params_from_file(path,
                                               use_default_template=False)

        for w in warns:
            message = 'In %s: %s' % (path, w.message)
            warnings.warn(message)

    return styles 
Example #8
Source File: core.py    From CogAlg with MIT License 5 votes vote down vote up
def read_style_directory(style_dir):
    """Return dictionary of styles defined in `style_dir`."""
    styles = dict()
    for path, name in iter_style_files(style_dir):
        with warnings.catch_warnings(record=True) as warns:
            styles[name] = rc_params_from_file(path,
                                               use_default_template=False)

        for w in warns:
            message = 'In %s: %s' % (path, w.message)
            _log.warning(message)

    return styles 
Example #9
Source File: test_rcparams.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_if_rctemplate_would_be_valid(tmpdir):
    # This tests if the matplotlibrc.template file would result in a valid
    # rc file if all lines are uncommented.
    path_to_rc = os.path.join(mpl.get_data_path(), 'matplotlibrc')
    with open(path_to_rc, "r") as f:
        rclines = f.readlines()
    newlines = []
    for line in rclines:
        if line[0] == "#":
            newline = line[1:]
        else:
            newline = line
        if "$TEMPLATE_BACKEND" in newline:
            newline = "backend : Agg"
        if "datapath" in newline:
            newline = ""
        newlines.append(newline)
    d = tmpdir.mkdir('test1')
    fname = str(d.join('testrcvalid.temp'))
    with open(fname, "w") as f:
        f.writelines(newlines)
    with pytest.warns(None) as record:
        mpl.rc_params_from_file(fname,
                                fail_on_error=True,
                                use_default_template=False)
        assert len(record) == 0 
Example #10
Source File: test_rcparams.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_Issue_1713():
    utf32_be = os.path.join(os.path.dirname(__file__),
                           'test_utf32_be_rcparams.rc')
    with mock.patch('locale.getpreferredencoding', return_value='UTF-32-BE'):
        rc = mpl.rc_params_from_file(utf32_be, True, False)
    assert rc.get('timezone') == 'UTC' 
Example #11
Source File: core.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def read_style_directory(style_dir):
    """Return dictionary of styles defined in `style_dir`."""
    styles = dict()
    for path, name in iter_style_files(style_dir):
        with warnings.catch_warnings(record=True) as warns:
            styles[name] = rc_params_from_file(path,
                                               use_default_template=False)

        for w in warns:
            message = 'In %s: %s' % (path, w.message)
            warnings.warn(message, stacklevel=2)

    return styles 
Example #12
Source File: theme_matplotlib.py    From plotnine with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, rc=None, fname=None, use_defaults=True):
        theme.__init__(
            self,
            aspect_ratio=get_option('aspect_ratio'),
            dpi=get_option('dpi'),
            figure_size=get_option('figure_size'),
            legend_key=element_rect(fill='None', colour='None'),
            legend_key_size=16,
            panel_spacing=0.1,
            strip_background=element_rect(
                fill='#D9D9D9', color='#D9D9D9', size=1),
            complete=True)

        if use_defaults:
            _copy = mpl.rcParams.copy()
            deprecated_rcparams = (
                set(mpl._deprecated_remain_as_none)
                | set(mpl._all_deprecated)
            )
            # no need to a get a deprecate warning just because
            # they are still included in rcParams...
            for key in deprecated_rcparams:
                if key in _copy:
                    del _copy[key]
            if 'tk.pythoninspect' in _copy:
                del _copy['tk.pythoninspect']
            self._rcParams.update(_copy)

        if fname:
            self._rcParams.update(mpl.rc_params_from_file(fname))
        if rc:
            self._rcParams.update(rc) 
Example #13
Source File: test_rcparams.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_if_rctemplate_would_be_valid(tmpdir):
    # This tests if the matplotlibrc.template file would result in a valid
    # rc file if all lines are uncommented.
    path_to_rc = os.path.join(mpl.get_data_path(), 'matplotlibrc')
    with open(path_to_rc, "r") as f:
        rclines = f.readlines()
    newlines = []
    for line in rclines:
        if line[0] == "#":
            newline = line[1:]
        else:
            newline = line
        if "$TEMPLATE_BACKEND" in newline:
            newline = "backend : Agg"
        if "datapath" in newline:
            newline = ""
        newlines.append(newline)
    d = tmpdir.mkdir('test1')
    fname = str(d.join('testrcvalid.temp'))
    with open(fname, "w") as f:
        f.writelines(newlines)
    with pytest.warns(None) as record:
        mpl.rc_params_from_file(fname,
                                fail_on_error=True,
                                use_default_template=False)
        assert len(record) == 0 
Example #14
Source File: test_rcparams.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_Issue_1713():
    utf32_be = os.path.join(os.path.dirname(__file__),
                           'test_utf32_be_rcparams.rc')
    with mock.patch('locale.getpreferredencoding', return_value='UTF-32-BE'):
        rc = mpl.rc_params_from_file(utf32_be, True, False)
    assert rc.get('timezone') == 'UTC' 
Example #15
Source File: core.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def read_style_directory(style_dir):
    """Return dictionary of styles defined in `style_dir`."""
    styles = dict()
    for path, name in iter_style_files(style_dir):
        with warnings.catch_warnings(record=True) as warns:
            styles[name] = rc_params_from_file(path,
                                               use_default_template=False)

        for w in warns:
            message = 'In %s: %s' % (path, w.message)
            warnings.warn(message, stacklevel=2)

    return styles 
Example #16
Source File: core.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def read_style_directory(style_dir):
    """Return dictionary of styles defined in `style_dir`."""
    styles = dict()
    for path, name in iter_style_files(style_dir):
        with warnings.catch_warnings(record=True) as warns:
            styles[name] = rc_params_from_file(path,
                                               use_default_template=False)

        for w in warns:
            message = 'In %s: %s' % (path, w.message)
            warnings.warn(message, stacklevel=2)

    return styles 
Example #17
Source File: core.py    From neural-network-animation with MIT License 5 votes vote down vote up
def read_style_directory(style_dir):
    """Return dictionary of styles defined in `style_dir`."""
    styles = dict()
    for path, name in iter_style_files(style_dir):
        styles[name] = rc_params_from_file(path, use_default_template=False)
    return styles 
Example #18
Source File: core.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def read_style_directory(style_dir):
    """Return dictionary of styles defined in `style_dir`."""
    styles = dict()
    for path, name in iter_style_files(style_dir):
        with warnings.catch_warnings(record=True) as warns:
            styles[name] = rc_params_from_file(path,
                                               use_default_template=False)

        for w in warns:
            message = 'In %s: %s' % (path, w.message)
            _log.warning(message)

    return styles 
Example #19
Source File: core.py    From Mastering-Elasticsearch-7.0 with MIT License 4 votes vote down vote up
def use(style):
    """Use matplotlib style settings from a style specification.

    The style name of 'default' is reserved for reverting back to
    the default style settings.

    Parameters
    ----------
    style : str, dict, or list
        A style specification. Valid options are:

        +------+-------------------------------------------------------------+
        | str  | The name of a style or a path/URL to a style file. For a    |
        |      | list of available style names, see `style.available`.       |
        +------+-------------------------------------------------------------+
        | dict | Dictionary with valid key/value pairs for                   |
        |      | `matplotlib.rcParams`.                                      |
        +------+-------------------------------------------------------------+
        | list | A list of style specifiers (str or dict) applied from first |
        |      | to last in the list.                                        |
        +------+-------------------------------------------------------------+


    """
    style_alias = {'mpl20': 'default',
                   'mpl15': 'classic'}
    if isinstance(style, str) or hasattr(style, 'keys'):
        # If name is a single str or dict, make it a single element list.
        styles = [style]
    else:
        styles = style

    styles = (style_alias.get(s, s) if isinstance(s, str) else s
              for s in styles)
    for style in styles:
        if not isinstance(style, str):
            _apply_style(style)
        elif style == 'default':
            # Deprecation warnings were already handled when creating
            # rcParamsDefault, no need to reemit them here.
            with cbook._suppress_matplotlib_deprecation_warning():
                _apply_style(rcParamsDefault, warn=False)
        elif style in library:
            _apply_style(library[style])
        else:
            try:
                rc = rc_params_from_file(style, use_default_template=False)
                _apply_style(rc)
            except IOError:
                raise IOError(
                    "{!r} not found in the style library and input is not a "
                    "valid URL or path; see `style.available` for list of "
                    "available styles".format(style)) 
Example #20
Source File: core.py    From coffeegrindsize with MIT License 4 votes vote down vote up
def use(style):
    """Use matplotlib style settings from a style specification.

    The style name of 'default' is reserved for reverting back to
    the default style settings.

    Parameters
    ----------
    style : str, dict, or list
        A style specification. Valid options are:

        +------+-------------------------------------------------------------+
        | str  | The name of a style or a path/URL to a style file. For a    |
        |      | list of available style names, see `style.available`.       |
        +------+-------------------------------------------------------------+
        | dict | Dictionary with valid key/value pairs for                   |
        |      | `matplotlib.rcParams`.                                      |
        +------+-------------------------------------------------------------+
        | list | A list of style specifiers (str or dict) applied from first |
        |      | to last in the list.                                        |
        +------+-------------------------------------------------------------+


    """
    style_alias = {'mpl20': 'default',
                   'mpl15': 'classic'}
    if isinstance(style, str) or hasattr(style, 'keys'):
        # If name is a single str or dict, make it a single element list.
        styles = [style]
    else:
        styles = style

    styles = (style_alias.get(s, s) if isinstance(s, str) else s
              for s in styles)
    for style in styles:
        if not isinstance(style, str):
            _apply_style(style)
        elif style == 'default':
            # Deprecation warnings were already handled when creating
            # rcParamsDefault, no need to reemit them here.
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", MatplotlibDeprecationWarning)
                _apply_style(rcParamsDefault, warn=False)
        elif style in library:
            _apply_style(library[style])
        else:
            try:
                rc = rc_params_from_file(style, use_default_template=False)
                _apply_style(rc)
            except IOError:
                raise IOError(
                    "{!r} not found in the style library and input is not a "
                    "valid URL or path; see `style.available` for list of "
                    "available styles".format(style)) 
Example #21
Source File: core.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def use(style):
    """Use matplotlib style settings from a style specification.

    The style name of 'default' is reserved for reverting back to
    the default style settings.

    Parameters
    ----------
    style : str, dict, or list
        A style specification. Valid options are:

        +------+-------------------------------------------------------------+
        | str  | The name of a style or a path/URL to a style file. For a    |
        |      | list of available style names, see `style.available`.       |
        +------+-------------------------------------------------------------+
        | dict | Dictionary with valid key/value pairs for                   |
        |      | `matplotlib.rcParams`.                                      |
        +------+-------------------------------------------------------------+
        | list | A list of style specifiers (str or dict) applied from first |
        |      | to last in the list.                                        |
        +------+-------------------------------------------------------------+


    """
    style_alias = {'mpl20': 'default',
                   'mpl15': 'classic'}
    if isinstance(style, str) or hasattr(style, 'keys'):
        # If name is a single str or dict, make it a single element list.
        styles = [style]
    else:
        styles = style

    styles = (style_alias.get(s, s) if isinstance(s, str) else s
              for s in styles)
    for style in styles:
        if not isinstance(style, str):
            _apply_style(style)
        elif style == 'default':
            # Deprecation warnings were already handled when creating
            # rcParamsDefault, no need to reemit them here.
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", MatplotlibDeprecationWarning)
                _apply_style(rcParamsDefault, warn=False)
        elif style in library:
            _apply_style(library[style])
        else:
            try:
                rc = rc_params_from_file(style, use_default_template=False)
                _apply_style(rc)
            except IOError:
                raise IOError(
                    "{!r} not found in the style library and input is not a "
                    "valid URL or path; see `style.available` for list of "
                    "available styles".format(style)) 
Example #22
Source File: core.py    From CogAlg with MIT License 4 votes vote down vote up
def use(style):
    """Use matplotlib style settings from a style specification.

    The style name of 'default' is reserved for reverting back to
    the default style settings.

    Parameters
    ----------
    style : str, dict, or list
        A style specification. Valid options are:

        +------+-------------------------------------------------------------+
        | str  | The name of a style or a path/URL to a style file. For a    |
        |      | list of available style names, see `style.available`.       |
        +------+-------------------------------------------------------------+
        | dict | Dictionary with valid key/value pairs for                   |
        |      | `matplotlib.rcParams`.                                      |
        +------+-------------------------------------------------------------+
        | list | A list of style specifiers (str or dict) applied from first |
        |      | to last in the list.                                        |
        +------+-------------------------------------------------------------+


    """
    style_alias = {'mpl20': 'default',
                   'mpl15': 'classic'}
    if isinstance(style, str) or hasattr(style, 'keys'):
        # If name is a single str or dict, make it a single element list.
        styles = [style]
    else:
        styles = style

    styles = (style_alias.get(s, s) if isinstance(s, str) else s
              for s in styles)
    for style in styles:
        if not isinstance(style, str):
            _apply_style(style)
        elif style == 'default':
            # Deprecation warnings were already handled when creating
            # rcParamsDefault, no need to reemit them here.
            with cbook._suppress_matplotlib_deprecation_warning():
                _apply_style(rcParamsDefault, warn=False)
        elif style in library:
            _apply_style(library[style])
        else:
            try:
                rc = rc_params_from_file(style, use_default_template=False)
                _apply_style(rc)
            except IOError:
                raise IOError(
                    "{!r} not found in the style library and input is not a "
                    "valid URL or path; see `style.available` for list of "
                    "available styles".format(style)) 
Example #23
Source File: core.py    From twitter-stock-recommendation with MIT License 4 votes vote down vote up
def use(style):
    """Use matplotlib style settings from a style specification.

    The style name of 'default' is reserved for reverting back to
    the default style settings.

    Parameters
    ----------
    style : str, dict, or list
        A style specification. Valid options are:

        +------+-------------------------------------------------------------+
        | str  | The name of a style or a path/URL to a style file. For a    |
        |      | list of available style names, see `style.available`.       |
        +------+-------------------------------------------------------------+
        | dict | Dictionary with valid key/value pairs for                   |
        |      | `matplotlib.rcParams`.                                      |
        +------+-------------------------------------------------------------+
        | list | A list of style specifiers (str or dict) applied from first |
        |      | to last in the list.                                        |
        +------+-------------------------------------------------------------+


    """
    style_alias = {'mpl20': 'default',
                   'mpl15': 'classic'}
    if isinstance(style, six.string_types) or hasattr(style, 'keys'):
        # If name is a single str or dict, make it a single element list.
        styles = [style]
    else:
        styles = style

    styles = (style_alias.get(s, s)
              if isinstance(s, six.string_types)
              else s
              for s in styles)
    for style in styles:
        if not isinstance(style, six.string_types):
            _apply_style(style)
        elif style == 'default':
            _apply_style(rcParamsDefault, warn=False)
        elif style in library:
            _apply_style(library[style])
        else:
            try:
                rc = rc_params_from_file(style, use_default_template=False)
                _apply_style(rc)
            except IOError:
                raise IOError(
                    "{!r} not found in the style library and input is not a "
                    "valid URL or path; see `style.available` for list of "
                    "available styles".format(style)) 
Example #24
Source File: core.py    From GraphicDesignPatternByPython with MIT License 4 votes vote down vote up
def use(style):
    """Use matplotlib style settings from a style specification.

    The style name of 'default' is reserved for reverting back to
    the default style settings.

    Parameters
    ----------
    style : str, dict, or list
        A style specification. Valid options are:

        +------+-------------------------------------------------------------+
        | str  | The name of a style or a path/URL to a style file. For a    |
        |      | list of available style names, see `style.available`.       |
        +------+-------------------------------------------------------------+
        | dict | Dictionary with valid key/value pairs for                   |
        |      | `matplotlib.rcParams`.                                      |
        +------+-------------------------------------------------------------+
        | list | A list of style specifiers (str or dict) applied from first |
        |      | to last in the list.                                        |
        +------+-------------------------------------------------------------+


    """
    style_alias = {'mpl20': 'default',
                   'mpl15': 'classic'}
    if isinstance(style, str) or hasattr(style, 'keys'):
        # If name is a single str or dict, make it a single element list.
        styles = [style]
    else:
        styles = style

    styles = (style_alias.get(s, s) if isinstance(s, str) else s
              for s in styles)
    for style in styles:
        if not isinstance(style, str):
            _apply_style(style)
        elif style == 'default':
            # Deprecation warnings were already handled when creating
            # rcParamsDefault, no need to reemit them here.
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", MatplotlibDeprecationWarning)
                _apply_style(rcParamsDefault, warn=False)
        elif style in library:
            _apply_style(library[style])
        else:
            try:
                rc = rc_params_from_file(style, use_default_template=False)
                _apply_style(rc)
            except IOError:
                raise IOError(
                    "{!r} not found in the style library and input is not a "
                    "valid URL or path; see `style.available` for list of "
                    "available styles".format(style))