Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Clarify tutorial "Customizing Matplotlib with style sheets and rcParams" #20812

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/matplotlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
19 changes: 14 additions & 5 deletions lib/matplotlib/style/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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`. |
Expand All @@ -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'}
Expand Down Expand Up @@ -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`. |
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/textpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <matplotlib-rcparams>`.
:ref:`rcParams<customizing-with-dynamic-rc-settings>`.

_interpolation_steps : int, optional
(Currently ignored)
Expand Down
9 changes: 5 additions & 4 deletions tutorials/intermediate/constrainedlayout_guide.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@

plt.subplots(constrained_layout=True)

* activate it via :ref:`rcParams<matplotlib-rcparams>`, like::
* activate it via :ref:`rcParams<customizing-with-dynamic-rc-settings>`,
like::

plt.rcParams['figure.constrained_layout.use'] = True

Expand Down Expand Up @@ -306,9 +307,9 @@ def example_plot(ax, fontsize=12, hide_labels=False):
# rcParams
# ========
#
# There are five :ref:`rcParams<matplotlib-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<customizing-with-dynamic-rc-settings>`
# 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.
Expand Down
190 changes: 107 additions & 83 deletions tutorials/introductory/customizing.py
Original file line number Diff line number Diff line change
@@ -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<customizing-with-dynamic-rc-settings>`.
2. :ref:`Using style sheets<customizing-with-style-sheets>`.
3. :ref:`Changing your matplotlibrc file<customizing-with-matplotlibrc-files>`.

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
<customizing-with-matplotlibrc-files>` file (which is read at startup to
configure Matplotlib).
Runtime rc settings
===================

There are a number of pre-defined styles :doc:`provided by Matplotlib
</gallery/style_sheets/style_sheets_reference>`. 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<matplotlibrc-sample>`
# 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
# </gallery/style_sheets/style_sheets_reference>`. 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:
Expand Down Expand Up @@ -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('<path>/<style-name>.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.
Expand All @@ -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<customizing-with-style-sheets>` is given with
# ``style.use('<path>/<style-name>.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::
Expand All @@ -214,12 +237,13 @@ def plotting_function():
# >>> matplotlib.matplotlib_fname()
# '/home/foo/.config/matplotlib/matplotlibrc'
#
# See below for a sample :ref:`matplotlibrc file<matplotlibrc-sample>`.
# See below for a sample :ref:`matplotlibrc file<matplotlibrc-sample>`
# 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
#
Expand Down