| def_rc_params_in_file(fname,transform=lambdax:x,fail_on_error=False): |
| """ |
| Construct a `RcParams` instance from file *fname*. |
| |
| Unlike `rc_params_from_file`, the configuration class only contains the |
| parameters specified in the file (i.e. default values are not filled in). |
| |
| Parameters |
| ---------- |
| fname : path-like |
| The loaded file. |
| transform : callable, default: the identity function |
| A function called on each individual line of the file to transform it, |
| before further parsing. |
| fail_on_error : bool, default: False |
| Whether invalid entries should result in an exception or a warning. |
| """ |
| importmatplotlibasmpl |
| rc_temp= {} |
| with_open_file_or_url(fname)asfd: |
| try: |
| forline_no,lineinenumerate(fd,1): |
| line=transform(line) |
| strippedline=cbook._strip_comment(line) |
| ifnotstrippedline: |
| continue |
| tup=strippedline.split(':',1) |
| iflen(tup)!=2: |
| _log.warning('Missing colon in file %r, line %d (%r)', |
| fname,line_no,line.rstrip('\n')) |
| continue |
| key,val=tup |
| key=key.strip() |
| val=val.strip() |
| ifval.startswith('"')andval.endswith('"'): |
| val=val[1:-1]# strip double quotes |
| ifkeyinrc_temp: |
| _log.warning('Duplicate key in file %r, line %d (%r)', |
| fname,line_no,line.rstrip('\n')) |
| rc_temp[key]= (val,line,line_no) |
| exceptUnicodeDecodeError: |
| _log.warning('Cannot decode configuration file %r as utf-8.', |
| fname) |
| raise |
| |
| config=RcParams() |
| |
| forkey, (val,line,line_no)inrc_temp.items(): |
| ifkeyinrcsetup._validators: |
| iffail_on_error: |
| config[key]=val# try to convert to proper type or raise |
| else: |
| try: |
| config[key]=val# try to convert to proper type or skip |
| exceptExceptionasmsg: |
| _log.warning('Bad value in file %r, line %d (%r): %s', |
| fname,line_no,line.rstrip('\n'),msg) |
| elifkeyin_deprecated_ignore_map: |
| version,alt_key=_deprecated_ignore_map[key] |
| _api.warn_deprecated( |
| version,name=key,alternative=alt_key,obj_type='rcparam', |
| addendum="Please update your matplotlibrc.") |
| else: |
| # __version__ must be looked up as an attribute to trigger the |
| # module-level __getattr__. |
| version= ('main'if'.post'inmpl.__version__ |
| elsef'v{mpl.__version__}') |
| _log.warning(""" |
| Bad key %(key)s in file %(fname)s, line %(line_no)s (%(line)r) |
| You probably need to get an updated matplotlibrc file from |
| https://github.com/matplotlib/matplotlib/blob/%(version)s/lib/matplotlib/mpl-data/matplotlibrc |
| or from the matplotlib source distribution""", |
| dict(key=key,fname=fname,line_no=line_no, |
| line=line.rstrip('\n'),version=version)) |
| returnconfig |
| |
| |
| defrc_params_from_file(fname,fail_on_error=False,use_default_template=True): |
| """ |
| Construct a `RcParams` from file *fname*. |
| |
| Parameters |
| ---------- |
| fname : str or path-like |
| A file with Matplotlib rc settings. |
| fail_on_error : bool |
| If True, raise an error when the parser fails to convert a parameter. |
| use_default_template : bool |
| If True, initialize with default parameters before updating with those |
| in the given file. If False, the configuration class only contains the |
| parameters specified in the file. (Useful for updating dicts.) |
| """ |
| config_from_file=_rc_params_in_file(fname,fail_on_error=fail_on_error) |
| |
| ifnotuse_default_template: |
| returnconfig_from_file |
| |
| with_api.suppress_matplotlib_deprecation_warning(): |
| config=RcParams({**rcParamsDefault,**config_from_file}) |
| |
| if"".join(config['text.latex.preamble']): |
| _log.info(""" |
| ***************************************************************** |
| You have the following UNSUPPORTED LaTeX preamble customizations: |
| %s |
| Please do not ask for support with these customizations active. |
| ***************************************************************** |
| """,'\n'.join(config['text.latex.preamble'])) |
| _log.debug('loaded rc file %s',fname) |
| |
| returnconfig |
| |
| |
| # When constructing the global instances, we need to perform certain updates |
| # by explicitly calling the superclass (dict.update, dict.items) to avoid |
| # triggering resolution of _auto_backend_sentinel. |
| rcParamsDefault=_rc_params_in_file( |
| cbook._get_data_path("matplotlibrc"), |
| # Strip leading comment. |
| transform=lambdaline:line[1:]ifline.startswith("#")elseline, |
| fail_on_error=True) |
| dict.update(rcParamsDefault,rcsetup._hardcoded_defaults) |
| # Normally, the default matplotlibrc file contains *no* entry for backend (the |
| # corresponding line starts with ##, not #; we fill on _auto_backend_sentinel |
| # in that case. However, packagers can set a different default backend |
| # (resulting in a normal `#backend: foo` line) in which case we should *not* |
| # fill in _auto_backend_sentinel. |
| dict.setdefault(rcParamsDefault,"backend",rcsetup._auto_backend_sentinel) |
| rcParams=RcParams()# The global instance. |
| dict.update(rcParams,dict.items(rcParamsDefault)) |
| dict.update(rcParams,_rc_params_in_file(matplotlib_fname())) |
| rcParamsOrig=rcParams.copy() |
| with_api.suppress_matplotlib_deprecation_warning(): |
| # This also checks that all rcParams are indeed listed in the template. |
| # Assigning to rcsetup.defaultParams is left only for backcompat. |
| defaultParams=rcsetup.defaultParams= { |
| # We want to resolve deprecated rcParams, but not backend... |
| key: [(rcsetup._auto_backend_sentinelifkey=="backend"else |
| rcParamsDefault[key]), |
| validator] |
| forkey,validatorinrcsetup._validators.items()} |
| ifrcParams['axes.formatter.use_locale']: |
| locale.setlocale(locale.LC_ALL,'') |
| |
| |
| defrc(group,**kwargs): |
| """ |
| Set the current `.rcParams`. *group* is the grouping for the rc, e.g., |
| for ``lines.linewidth`` the group is ``lines``, for |
| ``axes.facecolor``, the group is ``axes``, and so on. Group may |
| also be a list or tuple of group names, e.g., (*xtick*, *ytick*). |
| *kwargs* is a dictionary attribute name/value pairs, e.g.,:: |
| |
| rc('lines', linewidth=2, color='r') |
| |
| sets the current `.rcParams` and is equivalent to:: |
| |
| rcParams['lines.linewidth'] = 2 |
| rcParams['lines.color'] = 'r' |
| |
| The following aliases are available to save typing for interactive users: |
| |
| ===== ================= |
| Alias Property |
| ===== ================= |
| 'lw' 'linewidth' |
| 'ls' 'linestyle' |
| 'c' 'color' |
| 'fc' 'facecolor' |
| 'ec' 'edgecolor' |
| 'mew' 'markeredgewidth' |
| 'aa' 'antialiased' |
| ===== ================= |
| |
| Thus you could abbreviate the above call as:: |
| |
| rc('lines', lw=2, c='r') |
| |
| Note you can use python's kwargs dictionary facility to store |
| dictionaries of default parameters. e.g., you can customize the |
| font rc as follows:: |
| |
| font = {'family' : 'monospace', |
| 'weight' : 'bold', |
| 'size' : 'larger'} |
| rc('font', **font) # pass in the font dict as kwargs |
| |
| This enables you to easily switch between several configurations. Use |
| ``matplotlib.style.use('default')`` or :func:`~matplotlib.rcdefaults` to |
| restore the default `.rcParams` after changes. |
| |
| Notes |
| ----- |
| Similar functionality is available by using the normal dict interface, i.e. |
| ``rcParams.update({"lines.linewidth": 2, ...})`` (but ``rcParams.update`` |
| does not support abbreviations or grouping). |
| """ |
| |
| aliases= { |
| 'lw':'linewidth', |
| 'ls':'linestyle', |
| 'c':'color', |
| 'fc':'facecolor', |
| 'ec':'edgecolor', |
| 'mew':'markeredgewidth', |
| 'aa':'antialiased', |
| } |
| |
| ifisinstance(group,str): |
| group= (group,) |
| forgingroup: |
| fork,vinkwargs.items(): |
| name=aliases.get(k)ork |
| key=f'{g}.{name}' |
| try: |
| rcParams[key]=v |
| exceptKeyErroraserr: |
| raiseKeyError(('Unrecognized key "%s" for group "%s" and ' |
| 'name "%s"')% (key,g,name))fromerr |
| |
| |
| defrcdefaults(): |
| """ |
| Restore the `.rcParams` from Matplotlib's internal default style. |
| |
| Style-blacklisted `.rcParams` (defined in |
| ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated. |
| |
| See Also |
| -------- |
| matplotlib.rc_file_defaults |
| Restore the `.rcParams` from the rc file originally loaded by |
| Matplotlib. |
| matplotlib.style.use |
| Use a specific style file. Call ``style.use('default')`` to restore |
| the default style. |
| """ |
| # Deprecation warnings were already handled when creating rcParamsDefault, |
| # no need to reemit them here. |
| with_api.suppress_matplotlib_deprecation_warning(): |
| from .style.coreimportSTYLE_BLACKLIST |
| rcParams.clear() |
| rcParams.update({k:vfork,vinrcParamsDefault.items() |
| ifknotinSTYLE_BLACKLIST}) |
| |
| |
| defrc_file_defaults(): |
| """ |
| Restore the `.rcParams` from the original rc file loaded by Matplotlib. |
| |
| Style-blacklisted `.rcParams` (defined in |
| ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated. |
| """ |
| # Deprecation warnings were already handled when creating rcParamsOrig, no |
| # need to reemit them here. |
| with_api.suppress_matplotlib_deprecation_warning(): |
| from .style.coreimportSTYLE_BLACKLIST |
| rcParams.update({k:rcParamsOrig[k]forkinrcParamsOrig |
| ifknotinSTYLE_BLACKLIST}) |
| |
| |
| defrc_file(fname,*,use_default_template=True): |
| """ |
| Update `.rcParams` from file. |
| |
| Style-blacklisted `.rcParams` (defined in |
| ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated. |
| |
| Parameters |
| ---------- |
| fname : str or path-like |
| A file with Matplotlib rc settings. |
| |
| use_default_template : bool |
| If True, initialize with default parameters before updating with those |
| in the given file. If False, the current configuration persists |
| and only the parameters specified in the file are updated. |
| """ |
| # Deprecation warnings were already handled in rc_params_from_file, no need |
| # to reemit them here. |
| with_api.suppress_matplotlib_deprecation_warning(): |
| from .style.coreimportSTYLE_BLACKLIST |
| rc_from_file=rc_params_from_file( |
| fname,use_default_template=use_default_template) |
| rcParams.update({k:rc_from_file[k]forkinrc_from_file |
| ifknotinSTYLE_BLACKLIST}) |
| |
| |
| @contextlib.contextmanager |
| defrc_context(rc=None,fname=None): |
| """ |
| Return a context manager for temporarily changing rcParams. |
| |
| The :rc:`backend` will not be reset by the context manager. |
| |
| rcParams changed both through the context manager invocation and |
| in the body of the context will be reset on context exit. |
| |
| Parameters |
| ---------- |
| rc : dict |
| The rcParams to temporarily set. |
| fname : str or path-like |
| A file with Matplotlib rc settings. If both *fname* and *rc* are given, |
| settings from *rc* take precedence. |
| |
| See Also |
| -------- |
| :ref:`customizing-with-matplotlibrc-files` |
| |
| Examples |
| -------- |
| Passing explicit values via a dict:: |
| |
| with mpl.rc_context({'interactive': False}): |
| fig, ax = plt.subplots() |
| ax.plot(range(3), range(3)) |
| fig.savefig('example.png') |
| plt.close(fig) |
| |
| Loading settings from a file:: |
| |
| with mpl.rc_context(fname='print.rc'): |
| plt.plot(x, y) # uses 'print.rc' |
| |
| Setting in the context body:: |
| |
| with mpl.rc_context(): |
| # will be reset |
| mpl.rcParams['lines.linewidth'] = 5 |
| plt.plot(x, y) |
| |
| """ |
| orig=dict(rcParams.copy()) |
| delorig['backend'] |
| try: |
| iffname: |
| rc_file(fname) |
| ifrc: |
| rcParams.update(rc) |
| yield |
| finally: |
| dict.update(rcParams,orig)# Revert to the original rcs. |
Uh oh!
There was an error while loading.Please reload this page.
Disclaimer: This is very much work in progress and may substantially change before sent to review. But I want to give interested folks the opportunity to already have an early look.
Motivation
Until now, the parameter definition was dispersed: valid names and defaults are loaded from the canonical
matplotlibrc
data file. Docs are only available as comments in there. Validators are attached ad-hoc inrcsetup.py
.This makes for a more formal definition of parameters, including meta-information, like validators, docs in a single place. It will simplify the rcParams related code in
matplotlib.__init__.py
andmatplotlib.rcsetup.py
. It will also enable us to generate sphinx documentation on the parameters.Related:#23531,#4394
Scope / context
This can be seen in the context of the larger idea of re-designing the config system. However, for now the direct goal is to:
rcsetup
matplotlib/lib/matplotlib/__init__.py
Lines 847 to 1189 indbc906a
This can still be done with the current
RcParams
object in place.This definition will likely become private and users will still use
rcParams
,rcParamsDefault
etc. for the time being.