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

Skip to content

Commit 0a4a10c

Browse files
authored
Merge pull request #20812 from andthum/style-sheet-docs
Clarify tutorial "Customizing Matplotlib with style sheets and rcParams"
2 parents 5622be2 + 117b4a1 commit 0a4a10c

File tree

5 files changed

+130
-94
lines changed

5 files changed

+130
-94
lines changed

lib/matplotlib/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -597,7 +597,9 @@ def gen_candidates():
597597
_all_deprecated = {*_deprecated_map, *_deprecated_ignore_map}
598598

599599

600-
@docstring.Substitution("\n".join(map("- {}".format, rcsetup._validators)))
600+
@docstring.Substitution(
601+
"\n".join(map("- {}".format, sorted(rcsetup._validators, key=str.lower)))
602+
)
601603
class RcParams(MutableMapping, dict):
602604
"""
603605
A dictionary object including validation.

lib/matplotlib/style/core.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
import warnings
2121

2222
import matplotlib as mpl
23-
from matplotlib import _api, rc_params_from_file, rcParamsDefault
23+
from matplotlib import _api, docstring, rc_params_from_file, rcParamsDefault
2424

2525
_log = logging.getLogger(__name__)
2626

@@ -55,8 +55,8 @@ def _remove_blacklisted_style_params(d, warn=True):
5555
if key in STYLE_BLACKLIST:
5656
if warn:
5757
_api.warn_external(
58-
"Style includes a parameter, '{0}', that is not related "
59-
"to style. Ignoring".format(key))
58+
f"Style includes a parameter, {key!r}, that is not "
59+
"related to style. Ignoring this parameter.")
6060
else:
6161
o[key] = d[key]
6262
return o
@@ -66,6 +66,9 @@ def _apply_style(d, warn=True):
6666
mpl.rcParams.update(_remove_blacklisted_style_params(d, warn=warn))
6767

6868

69+
@docstring.Substitution(
70+
"\n".join(map("- {}".format, sorted(STYLE_BLACKLIST, key=str.lower)))
71+
)
6972
def use(style):
7073
"""
7174
Use Matplotlib style settings from a style specification.
@@ -85,7 +88,7 @@ def use(style):
8588
8689
+------+-------------------------------------------------------------+
8790
| str | The name of a style or a path/URL to a style file. For a |
88-
| | list of available style names, see `style.available`. |
91+
| | list of available style names, see `.style.available`. |
8992
+------+-------------------------------------------------------------+
9093
| dict | Dictionary with valid key/value pairs for |
9194
| | `matplotlib.rcParams`. |
@@ -96,6 +99,12 @@ def use(style):
9699
| | first to last in the list. |
97100
+------+-------------------------------------------------------------+
98101
102+
Notes
103+
-----
104+
The following `.rcParams` are not related to style and will be ignored if
105+
found in a style specification:
106+
107+
%s
99108
"""
100109
style_alias = {'mpl20': 'default',
101110
'mpl15': 'classic'}
@@ -140,7 +149,7 @@ def context(style, after_reset=False):
140149
141150
+------+-------------------------------------------------------------+
142151
| str | The name of a style or a path/URL to a style file. For a |
143-
| | list of available style names, see `style.available`. |
152+
| | list of available style names, see `.style.available`. |
144153
+------+-------------------------------------------------------------+
145154
| dict | Dictionary with valid key/value pairs for |
146155
| | `matplotlib.rcParams`. |

lib/matplotlib/textpath.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,7 @@ def __init__(self, xy, s, size=None, prop=None,
351351
prop : `matplotlib.font_manager.FontProperties`, optional
352352
Font property. If not provided, will use a default
353353
``FontProperties`` with parameters from the
354-
:ref:`rcParams <matplotlib-rcparams>`.
354+
:ref:`rcParams<customizing-with-dynamic-rc-settings>`.
355355
356356
_interpolation_steps : int, optional
357357
(Currently ignored)

tutorials/intermediate/constrainedlayout_guide.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222
2323
plt.subplots(constrained_layout=True)
2424
25-
* activate it via :ref:`rcParams<matplotlib-rcparams>`, like::
25+
* activate it via :ref:`rcParams<customizing-with-dynamic-rc-settings>`,
26+
like::
2627
2728
plt.rcParams['figure.constrained_layout.use'] = True
2829
@@ -305,9 +306,9 @@ def example_plot(ax, fontsize=12, hide_labels=False):
305306
# rcParams
306307
# ========
307308
#
308-
# There are five :ref:`rcParams<matplotlib-rcparams>` that can be set,
309-
# either in a script or in the :file:`matplotlibrc` file.
310-
# They all have the prefix ``figure.constrained_layout``:
309+
# There are five :ref:`rcParams<customizing-with-dynamic-rc-settings>`
310+
# that can be set, either in a script or in the :file:`matplotlibrc`
311+
# file. They all have the prefix ``figure.constrained_layout``:
311312
#
312313
# - *use*: Whether to use constrained_layout. Default is False
313314
# - *w_pad*, *h_pad*: Padding around axes objects.

tutorials/introductory/customizing.py

Lines changed: 107 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,113 @@
11
"""
22
.. redirect-from:: /users/customizing
33
4+
=====================================================
45
Customizing Matplotlib with style sheets and rcParams
56
=====================================================
67
78
Tips for customizing the properties and default styles of Matplotlib.
89
9-
Using style sheets
10-
------------------
10+
There are three ways to customize Matplotlib:
11+
12+
1. :ref:`Setting rcParams at runtime<customizing-with-dynamic-rc-settings>`.
13+
2. :ref:`Using style sheets<customizing-with-style-sheets>`.
14+
3. :ref:`Changing your matplotlibrc file<customizing-with-matplotlibrc-files>`.
15+
16+
Setting rcParams at runtime takes precedence over style sheets, style
17+
sheets take precedence over :file:`matplotlibrc` files.
18+
19+
.. _customizing-with-dynamic-rc-settings:
1120
12-
The :mod:`.style` package adds support for easy-to-switch plotting
13-
"styles" with the same parameters as a :ref:`matplotlib rc
14-
<customizing-with-matplotlibrc-files>` file (which is read at startup to
15-
configure Matplotlib).
21+
Runtime rc settings
22+
===================
1623
17-
There are a number of pre-defined styles :doc:`provided by Matplotlib
18-
</gallery/style_sheets/style_sheets_reference>`. For
19-
example, there's a pre-defined style called "ggplot", which emulates the
20-
aesthetics of ggplot_ (a popular plotting package for R_). To use this style,
21-
just add:
24+
You can dynamically change the default rc (runtime configuration)
25+
settings in a python script or interactively from the python shell. All
26+
rc settings are stored in a dictionary-like variable called
27+
:data:`matplotlib.rcParams`, which is global to the matplotlib package.
28+
See `matplotlib.rcParams` for a full list of configurable rcParams.
29+
rcParams can be modified directly, for example:
2230
"""
2331

2432
import numpy as np
2533
import matplotlib.pyplot as plt
2634
import matplotlib as mpl
2735
from cycler import cycler
28-
plt.style.use('ggplot')
36+
mpl.rcParams['lines.linewidth'] = 2
37+
mpl.rcParams['lines.linestyle'] = '--'
2938
data = np.random.randn(50)
39+
plt.plot(data)
40+
41+
###############################################################################
42+
# Note, that in order to change the usual `~.Axes.plot` color you have to
43+
# change the *prop_cycle* property of *axes*:
44+
45+
mpl.rcParams['axes.prop_cycle'] = cycler(color=['r', 'g', 'b', 'y'])
46+
plt.plot(data) # first color is red
47+
48+
###############################################################################
49+
# Matplotlib also provides a couple of convenience functions for modifying rc
50+
# settings. `matplotlib.rc` can be used to modify multiple
51+
# settings in a single group at once, using keyword arguments:
52+
53+
mpl.rc('lines', linewidth=4, linestyle='-.')
54+
plt.plot(data)
55+
56+
###############################################################################
57+
# Temporary rc settings
58+
# ---------------------
59+
#
60+
# The :data:`matplotlib.rcParams` object can also be changed temporarily using
61+
# the `matplotlib.rc_context` context manager:
62+
63+
with mpl.rc_context({'lines.linewidth': 2, 'lines.linestyle': ':'}):
64+
plt.plot(data)
65+
66+
###############################################################################
67+
# `matplotlib.rc_context` can also be used as a decorator to modify the
68+
# defaults within a function:
69+
70+
71+
@mpl.rc_context({'lines.linewidth': 3, 'lines.linestyle': '-'})
72+
def plotting_function():
73+
plt.plot(data)
74+
75+
plotting_function()
76+
77+
###############################################################################
78+
# `matplotlib.rcdefaults` will restore the standard Matplotlib
79+
# default settings.
80+
#
81+
# There is some degree of validation when setting the values of rcParams, see
82+
# :mod:`matplotlib.rcsetup` for details.
83+
84+
###############################################################################
85+
# .. _customizing-with-style-sheets:
86+
#
87+
# Using style sheets
88+
# ==================
89+
#
90+
# Another way to change the visual appearance of plots is to set the
91+
# rcParams in a so-called style sheet and import that style sheet with
92+
# `matplotlib.style.use`. In this way you can switch easily between
93+
# different styles by simply changing the imported style sheet. A style
94+
# sheets looks the same as a :ref:`matplotlibrc<matplotlibrc-sample>`
95+
# file, but in a style sheet you can only set rcParams that are related
96+
# to the actual style of a plot. Other rcParams, like *backend*, will be
97+
# ignored. :file:`matplotlibrc` files support all rcParams. The
98+
# rationale behind this is to make style sheets portable between
99+
# different machines without having to worry about dependencies which
100+
# might or might not be installed on another machine. For a full list of
101+
# rcParams see `matplotlib.rcParams`. For a list of rcParams that are
102+
# ignored in style sheets see `matplotlib.style.use`.
103+
#
104+
# There are a number of pre-defined styles :doc:`provided by Matplotlib
105+
# </gallery/style_sheets/style_sheets_reference>`. For
106+
# example, there's a pre-defined style called "ggplot", which emulates the
107+
# aesthetics of ggplot_ (a popular plotting package for R_). To use this
108+
# style, add:
109+
110+
plt.style.use('ggplot')
30111

31112
###############################################################################
32113
# To list all available styles, use:
@@ -104,80 +185,18 @@
104185
plt.show()
105186

106187
###############################################################################
107-
# .. _matplotlib-rcparams:
108-
#
109-
# Matplotlib rcParams
110-
# ===================
111-
#
112-
# .. _customizing-with-dynamic-rc-settings:
113-
#
114-
# Dynamic rc settings
115-
# -------------------
116-
#
117-
# You can also dynamically change the default rc settings in a python script or
118-
# interactively from the python shell. All of the rc settings are stored in a
119-
# dictionary-like variable called :data:`matplotlib.rcParams`, which is global to
120-
# the matplotlib package. rcParams can be modified directly, for example:
121-
122-
mpl.rcParams['lines.linewidth'] = 2
123-
mpl.rcParams['lines.linestyle'] = '--'
124-
plt.plot(data)
125-
126-
###############################################################################
127-
# Note, that in order to change the usual `~.Axes.plot` color you have to
128-
# change the *prop_cycle* property of *axes*:
129-
130-
mpl.rcParams['axes.prop_cycle'] = cycler(color=['r', 'g', 'b', 'y'])
131-
plt.plot(data) # first color is red
132-
133-
###############################################################################
134-
# Matplotlib also provides a couple of convenience functions for modifying rc
135-
# settings. `matplotlib.rc` can be used to modify multiple
136-
# settings in a single group at once, using keyword arguments:
137-
138-
mpl.rc('lines', linewidth=4, linestyle='-.')
139-
plt.plot(data)
140-
141-
###############################################################################
142-
# Temporary rc settings
143-
# ---------------------
144-
#
145-
# The :data:`matplotlib.rcParams` object can also be changed temporarily using
146-
# the `matplotlib.rc_context` context manager:
147-
148-
with mpl.rc_context({'lines.linewidth': 2, 'lines.linestyle': ':'}):
149-
plt.plot(data)
150-
151-
###############################################################################
152-
# `matplotlib.rc_context` can also be used as a decorator to modify the
153-
# defaults within a function:
154-
155-
156-
@mpl.rc_context({'lines.linewidth': 3, 'lines.linestyle': '-'})
157-
def plotting_function():
158-
plt.plot(data)
159-
160-
plotting_function()
161-
162-
###############################################################################
163-
# `matplotlib.rcdefaults` will restore the standard Matplotlib
164-
# default settings.
165-
#
166-
# There is some degree of validation when setting the values of rcParams, see
167-
# :mod:`matplotlib.rcsetup` for details.
168-
#
169188
# .. _customizing-with-matplotlibrc-files:
170189
#
171190
# The :file:`matplotlibrc` file
172-
# -----------------------------
191+
# =============================
173192
#
174193
# Matplotlib uses :file:`matplotlibrc` configuration files to customize all
175194
# kinds of properties, which we call 'rc settings' or 'rc parameters'. You can
176195
# control the defaults of almost every property in Matplotlib: figure size and
177196
# DPI, line width, color and style, axes, axis and grid properties, text and
178-
# font properties and so on. When a URL or path is not specified with a call to
179-
# ``style.use('<path>/<style-name>.mplstyle')``, Matplotlib looks for
180-
# :file:`matplotlibrc` in four locations, in the following order:
197+
# font properties and so on. The :file:`matplotlibrc` is read at startup to
198+
# configure Matplotlib. Matplotlib looks for :file:`matplotlibrc` in four
199+
# locations, in the following order:
181200
#
182201
# 1. :file:`matplotlibrc` in the current working directory, usually used for
183202
# specific customizations that you do not want to apply elsewhere.
@@ -204,8 +223,12 @@ def plotting_function():
204223
# your customizations to be saved, please move this file to your
205224
# user-specific matplotlib directory.
206225
#
207-
# Once a :file:`matplotlibrc` file has been found, it will *not* search any of
208-
# the other paths.
226+
# Once a :file:`matplotlibrc` file has been found, it will *not* search
227+
# any of the other paths. When a
228+
# :ref:`style sheet<customizing-with-style-sheets>` is given with
229+
# ``style.use('<path>/<style-name>.mplstyle')``, settings specified in
230+
# the style sheet take precedence over settings in the
231+
# :file:`matplotlibrc` file.
209232
#
210233
# To display where the currently active :file:`matplotlibrc` file was
211234
# loaded from, one can do the following::
@@ -214,12 +237,13 @@ def plotting_function():
214237
# >>> matplotlib.matplotlib_fname()
215238
# '/home/foo/.config/matplotlib/matplotlibrc'
216239
#
217-
# See below for a sample :ref:`matplotlibrc file<matplotlibrc-sample>`.
240+
# See below for a sample :ref:`matplotlibrc file<matplotlibrc-sample>`
241+
# and see `matplotlib.rcParams` for a full list of configurable rcParams.
218242
#
219243
# .. _matplotlibrc-sample:
220244
#
221-
# A sample matplotlibrc file
222-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~
245+
# The default :file:`matplotlibrc` file
246+
# -------------------------------------
223247
#
224248
# .. literalinclude:: ../../../lib/matplotlib/mpl-data/matplotlibrc
225249
#

0 commit comments

Comments
 (0)