diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index cfc3db4f7b27..65ffb379358f 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -597,7 +597,9 @@ def gen_candidates(): _all_deprecated = {*_deprecated_map, *_deprecated_ignore_map} -@docstring.Substitution("\n".join(map("- {}".format, rcsetup._validators))) +@docstring.Substitution( + "\n".join(map("- {}".format, sorted(rcsetup._validators, key=str.lower))) +) class RcParams(MutableMapping, dict): """ A dictionary object including validation. diff --git a/lib/matplotlib/style/core.py b/lib/matplotlib/style/core.py index d0592bd32201..e2f198ed469c 100644 --- a/lib/matplotlib/style/core.py +++ b/lib/matplotlib/style/core.py @@ -20,7 +20,7 @@ import warnings import matplotlib as mpl -from matplotlib import _api, rc_params_from_file, rcParamsDefault +from matplotlib import _api, docstring, rc_params_from_file, rcParamsDefault _log = logging.getLogger(__name__) @@ -54,8 +54,8 @@ def _remove_blacklisted_style_params(d, warn=True): if key in STYLE_BLACKLIST: if warn: _api.warn_external( - "Style includes a parameter, '{0}', that is not related " - "to style. Ignoring".format(key)) + f"Style includes a parameter, {key!r}, that is not " + "related to style. Ignoring this parameter.") else: o[key] = d[key] return o @@ -65,6 +65,9 @@ def _apply_style(d, warn=True): mpl.rcParams.update(_remove_blacklisted_style_params(d, warn=warn)) +@docstring.Substitution( + "\n".join(map("- {}".format, sorted(STYLE_BLACKLIST, key=str.lower))) +) def use(style): """ Use Matplotlib style settings from a style specification. @@ -84,7 +87,7 @@ def use(style): +------+-------------------------------------------------------------+ | str | The name of a style or a path/URL to a style file. For a | - | | list of available style names, see `style.available`. | + | | list of available style names, see `.style.available`. | +------+-------------------------------------------------------------+ | dict | Dictionary with valid key/value pairs for | | | `matplotlib.rcParams`. | @@ -95,6 +98,12 @@ def use(style): | | first to last in the list. | +------+-------------------------------------------------------------+ + Notes + ----- + The following `.rcParams` are not related to style and will be ignored if + found in a style specification: + + %s """ style_alias = {'mpl20': 'default', 'mpl15': 'classic'} @@ -139,7 +148,7 @@ def context(style, after_reset=False): +------+-------------------------------------------------------------+ | str | The name of a style or a path/URL to a style file. For a | - | | list of available style names, see `style.available`. | + | | list of available style names, see `.style.available`. | +------+-------------------------------------------------------------+ | dict | Dictionary with valid key/value pairs for | | | `matplotlib.rcParams`. | diff --git a/lib/matplotlib/textpath.py b/lib/matplotlib/textpath.py index babb89c67899..9b14e79ec2d2 100644 --- a/lib/matplotlib/textpath.py +++ b/lib/matplotlib/textpath.py @@ -351,7 +351,7 @@ def __init__(self, xy, s, size=None, prop=None, prop : `matplotlib.font_manager.FontProperties`, optional Font property. If not provided, will use a default ``FontProperties`` with parameters from the - :ref:`rcParams `. + :ref:`rcParams`. _interpolation_steps : int, optional (Currently ignored) diff --git a/tutorials/intermediate/constrainedlayout_guide.py b/tutorials/intermediate/constrainedlayout_guide.py index 2c76c4c0327d..379417e07fee 100644 --- a/tutorials/intermediate/constrainedlayout_guide.py +++ b/tutorials/intermediate/constrainedlayout_guide.py @@ -22,7 +22,8 @@ plt.subplots(constrained_layout=True) -* activate it via :ref:`rcParams`, like:: +* activate it via :ref:`rcParams`, + like:: plt.rcParams['figure.constrained_layout.use'] = True @@ -306,9 +307,9 @@ def example_plot(ax, fontsize=12, hide_labels=False): # rcParams # ======== # -# There are five :ref:`rcParams` that can be set, -# either in a script or in the :file:`matplotlibrc` file. -# They all have the prefix ``figure.constrained_layout``: +# There are five :ref:`rcParams` +# that can be set, either in a script or in the :file:`matplotlibrc` +# file. They all have the prefix ``figure.constrained_layout``: # # - *use*: Whether to use constrained_layout. Default is False # - *w_pad*, *h_pad*: Padding around axes objects. diff --git a/tutorials/introductory/customizing.py b/tutorials/introductory/customizing.py index 9eb6e17126ee..9e74016c823e 100644 --- a/tutorials/introductory/customizing.py +++ b/tutorials/introductory/customizing.py @@ -1,32 +1,113 @@ """ .. redirect-from:: /users/customizing +===================================================== Customizing Matplotlib with style sheets and rcParams ===================================================== Tips for customizing the properties and default styles of Matplotlib. -Using style sheets ------------------- +There are three ways to customize Matplotlib: + + 1. :ref:`Setting rcParams at runtime`. + 2. :ref:`Using style sheets`. + 3. :ref:`Changing your matplotlibrc file`. + +Setting rcParams at runtime takes precedence over style sheets, style +sheets take precedence over :file:`matplotlibrc` files. + +.. _customizing-with-dynamic-rc-settings: -The :mod:`.style` package adds support for easy-to-switch plotting -"styles" with the same parameters as a :ref:`matplotlib rc -` file (which is read at startup to -configure Matplotlib). +Runtime rc settings +=================== -There are a number of pre-defined styles :doc:`provided by Matplotlib -`. For -example, there's a pre-defined style called "ggplot", which emulates the -aesthetics of ggplot_ (a popular plotting package for R_). To use this style, -just add: +You can dynamically change the default rc (runtime configuration) +settings in a python script or interactively from the python shell. All +rc settings are stored in a dictionary-like variable called +:data:`matplotlib.rcParams`, which is global to the matplotlib package. +See `matplotlib.rcParams` for a full list of configurable rcParams. +rcParams can be modified directly, for example: """ import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from cycler import cycler -plt.style.use('ggplot') +mpl.rcParams['lines.linewidth'] = 2 +mpl.rcParams['lines.linestyle'] = '--' data = np.random.randn(50) +plt.plot(data) + +############################################################################### +# Note, that in order to change the usual `~.Axes.plot` color you have to +# change the *prop_cycle* property of *axes*: + +mpl.rcParams['axes.prop_cycle'] = cycler(color=['r', 'g', 'b', 'y']) +plt.plot(data) # first color is red + +############################################################################### +# Matplotlib also provides a couple of convenience functions for modifying rc +# settings. `matplotlib.rc` can be used to modify multiple +# settings in a single group at once, using keyword arguments: + +mpl.rc('lines', linewidth=4, linestyle='-.') +plt.plot(data) + +############################################################################### +# Temporary rc settings +# --------------------- +# +# The :data:`matplotlib.rcParams` object can also be changed temporarily using +# the `matplotlib.rc_context` context manager: + +with mpl.rc_context({'lines.linewidth': 2, 'lines.linestyle': ':'}): + plt.plot(data) + +############################################################################### +# `matplotlib.rc_context` can also be used as a decorator to modify the +# defaults within a function: + + +@mpl.rc_context({'lines.linewidth': 3, 'lines.linestyle': '-'}) +def plotting_function(): + plt.plot(data) + +plotting_function() + +############################################################################### +# `matplotlib.rcdefaults` will restore the standard Matplotlib +# default settings. +# +# There is some degree of validation when setting the values of rcParams, see +# :mod:`matplotlib.rcsetup` for details. + +############################################################################### +# .. _customizing-with-style-sheets: +# +# Using style sheets +# ================== +# +# Another way to change the visual appearance of plots is to set the +# rcParams in a so-called style sheet and import that style sheet with +# `matplotlib.style.use`. In this way you can switch easily between +# different styles by simply changing the imported style sheet. A style +# sheets looks the same as a :ref:`matplotlibrc` +# file, but in a style sheet you can only set rcParams that are related +# to the actual style of a plot. Other rcParams, like *backend*, will be +# ignored. :file:`matplotlibrc` files support all rcParams. The +# rationale behind this is to make style sheets portable between +# different machines without having to worry about dependencies which +# might or might not be installed on another machine. For a full list of +# rcParams see `matplotlib.rcParams`. For a list of rcParams that are +# ignored in style sheets see `matplotlib.style.use`. +# +# There are a number of pre-defined styles :doc:`provided by Matplotlib +# `. For +# example, there's a pre-defined style called "ggplot", which emulates the +# aesthetics of ggplot_ (a popular plotting package for R_). To use this +# style, add: + +plt.style.use('ggplot') ############################################################################### # To list all available styles, use: @@ -104,80 +185,18 @@ plt.show() ############################################################################### -# .. _matplotlib-rcparams: -# -# Matplotlib rcParams -# =================== -# -# .. _customizing-with-dynamic-rc-settings: -# -# Dynamic rc settings -# ------------------- -# -# You can also dynamically change the default rc settings in a python script or -# interactively from the python shell. All of the rc settings are stored in a -# dictionary-like variable called :data:`matplotlib.rcParams`, which is global to -# the matplotlib package. rcParams can be modified directly, for example: - -mpl.rcParams['lines.linewidth'] = 2 -mpl.rcParams['lines.linestyle'] = '--' -plt.plot(data) - -############################################################################### -# Note, that in order to change the usual `~.Axes.plot` color you have to -# change the *prop_cycle* property of *axes*: - -mpl.rcParams['axes.prop_cycle'] = cycler(color=['r', 'g', 'b', 'y']) -plt.plot(data) # first color is red - -############################################################################### -# Matplotlib also provides a couple of convenience functions for modifying rc -# settings. `matplotlib.rc` can be used to modify multiple -# settings in a single group at once, using keyword arguments: - -mpl.rc('lines', linewidth=4, linestyle='-.') -plt.plot(data) - -############################################################################### -# Temporary rc settings -# --------------------- -# -# The :data:`matplotlib.rcParams` object can also be changed temporarily using -# the `matplotlib.rc_context` context manager: - -with mpl.rc_context({'lines.linewidth': 2, 'lines.linestyle': ':'}): - plt.plot(data) - -############################################################################### -# `matplotlib.rc_context` can also be used as a decorator to modify the -# defaults within a function: - - -@mpl.rc_context({'lines.linewidth': 3, 'lines.linestyle': '-'}) -def plotting_function(): - plt.plot(data) - -plotting_function() - -############################################################################### -# `matplotlib.rcdefaults` will restore the standard Matplotlib -# default settings. -# -# There is some degree of validation when setting the values of rcParams, see -# :mod:`matplotlib.rcsetup` for details. -# # .. _customizing-with-matplotlibrc-files: # # The :file:`matplotlibrc` file -# ----------------------------- +# ============================= # # Matplotlib uses :file:`matplotlibrc` configuration files to customize all # kinds of properties, which we call 'rc settings' or 'rc parameters'. You can # control the defaults of almost every property in Matplotlib: figure size and # DPI, line width, color and style, axes, axis and grid properties, text and -# font properties and so on. When a URL or path is not specified with a call to -# ``style.use('/.mplstyle')``, Matplotlib looks for -# :file:`matplotlibrc` in four locations, in the following order: +# font properties and so on. The :file:`matplotlibrc` is read at startup to +# configure Matplotlib. Matplotlib looks for :file:`matplotlibrc` in four +# locations, in the following order: # # 1. :file:`matplotlibrc` in the current working directory, usually used for # specific customizations that you do not want to apply elsewhere. @@ -204,8 +223,12 @@ def plotting_function(): # your customizations to be saved, please move this file to your # user-specific matplotlib directory. # -# Once a :file:`matplotlibrc` file has been found, it will *not* search any of -# the other paths. +# Once a :file:`matplotlibrc` file has been found, it will *not* search +# any of the other paths. When a +# :ref:`style sheet` is given with +# ``style.use('/.mplstyle')``, settings specified in +# the style sheet take precedence over settings in the +# :file:`matplotlibrc` file. # # To display where the currently active :file:`matplotlibrc` file was # loaded from, one can do the following:: @@ -214,12 +237,13 @@ def plotting_function(): # >>> matplotlib.matplotlib_fname() # '/home/foo/.config/matplotlib/matplotlibrc' # -# See below for a sample :ref:`matplotlibrc file`. +# See below for a sample :ref:`matplotlibrc file` +# and see `matplotlib.rcParams` for a full list of configurable rcParams. # # .. _matplotlibrc-sample: # -# A sample matplotlibrc file -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ +# The default :file:`matplotlibrc` file +# ------------------------------------- # # .. literalinclude:: ../../../lib/matplotlib/mpl-data/matplotlibrc #