Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 57 ยท Annotation and Polish

Styles, rcParams and Themes

Give every chart the same look. Learn plt.style.use, rcParams, rc_context, color cyclers, dark backgrounds and your own style dictionary.

So far you styled charts one call at a time: a color here, a font size there. That works for a single figure, but it does not scale. If a report has twelve charts, you do not want to repeat the same ten lines twelve times, and you certainly do not want chart seven to be slightly different from chart eight.

Matplotlib solves this with runtime configuration, a big dictionary of defaults called rcParams. A style is just a bundle of rcParams values with a name. In this lesson you will switch between built-in styles, change single defaults, change them only temporarily, build a custom color cycle and write your own theme once so every chart can reuse it.

Three levels of control

Style A named bundle of defaults.
rcParams One global dictionary of settings.
rc_context Change settings for a block only.

Explicit arguments on a call always beat all three.

1 / 2

Built-in styles

plt.style.use("name") applies a style to every figure you create afterwards. Matplotlib ships with a list of them in plt.style.available. The exact list can change between versions, so check before you depend on a name.

Python Check which styles exist

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Names that start with seaborn-v0_8 are the old seaborn looks, kept inside Matplotlib. They exist even though the seaborn library itself is not needed.

The best way to choose is to look. The next example draws the same data in four styles. It uses plt.style.context(...), a with block that applies a style only inside the block, so the styles do not pile on top of each other.

Python The same data in four styles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the style is read when each Axes is created. That is why the add_subplot call sits inside the with block. Create the Axes outside the block and the style will not apply.

You can also combine styles. Pass a list and later entries override earlier ones: plt.style.use(["ggplot", "dark_background"]).

plt.style.use() changes the state for the rest of the session. On this site each run starts fresh, but in a notebook or a long script a forgotten style.use quietly changes every later chart. Prefer plt.style.context() when you only want a temporary look.

Besides the common ggplot, bmh and dark_background, the library has many more looks. A few worth knowing:

Style Character
Solarize_Light2 warm, low-contrast beige background from the Solarized palette; easy on the eyes
seaborn-v0_8-darkgrid grey panel with white grid lines, the classic seaborn look
tableau-colorblind10 ten colors chosen to stay distinguishable for color-blind readers
grayscale black, white and greys only; use it to check that a chart survives black-and-white printing
classic the look of Matplotlib 1.x, with thin lines and a white box
fast simplifies paths so charts with millions of points draw faster

Apply one with plt.style.use("Solarize_Light2"), or with the with plt.style.context(...) form for a single figure. Style names are case sensitive (note the capital letters in Solarize_Light2), and a name that does not exist raises an OSError, so print plt.style.available when in doubt.

Python Six more styles side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The three lines in each panel use the style's own color cycle, which is the easiest way to see how a style picks colors. Remember that a style only affects Axes created inside its with block.

rcParams: the dictionary behind everything

plt.rcParams behaves like a dictionary. Keys use a dotted naming scheme: lines.linewidth, font.size, axes.grid, figure.dpi. Read a value by indexing, set it by assigning.

Python Reading and setting rcParams

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A handful of keys give the biggest visual payoff:

Key What it controls
font.size, font.family Base text size and typeface
axes.titlesize, axes.labelsize Title and axis label sizes (can be relative, such as "large")
lines.linewidth, lines.markersize Default line thickness and marker size
axes.prop_cycle The sequence of colors, line styles and markers
axes.grid, grid.alpha Whether a grid shows and how strong it is
axes.spines.top, axes.spines.right Show or hide the box edges
figure.figsize, figure.dpi Default size and resolution
axes.facecolor, figure.facecolor Background colors

To see every key, print plt.rcParams.keys(). There are several hundred, so search them rather than read them: [k for k in plt.rcParams if k.startswith("legend.")].

Temporary changes with rc_context

Changing a global and then remembering to change it back is error-prone. plt.rc_context() takes a dictionary of changes and restores everything when the block ends, even if an error occurs.

Python rc_context restores the old values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first chart uses the normal 10-point text and the second uses 14. Just like with style.context, the setting takes effect when an artist is created or its text is set inside the block, so keep all the plotting calls inside it.

rc_context is the right tool for a helper function that wants its own look without touching anything else.

Custom color cycles with cycler

When you call ax.plot several times without a color, Matplotlib walks through a cycle stored in axes.prop_cycle. The default is ten colors named C0 to C9. You can replace it using the cycler package that Matplotlib depends on.

Cyclers can be added (+, advancing together like zip) or multiplied (*, every combination). Adding colors and line styles together is a good accessibility trick: the lines stay distinguishable in grayscale.

Python A color-and-linestyle cycle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

ax.set_prop_cycle(cycle) changes one Axes. To change the default for all new Axes, set plt.rcParams["axes.prop_cycle"] = cycle. A cycle with four entries repeats on the fifth line, so give it at least as many entries as the lines you draw.

Building your own theme

A custom style is a dictionary. Keep it in one place, apply it with plt.rcParams.update() or rc_context, and every chart in the project looks related.

Python A reusable house style

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Both charts share the left-aligned bold titles, light grid sitting behind the data, missing top and right spines and the same colors. To use a theme across files, save the same keys in a text file called house.mplstyle with one key: value pair per line (for example axes.grid: True) and load it with plt.style.use("house.mplstyle"). Files are not available in the browser here, so the dictionary form is the one to practice.

Dark backgrounds

The dark_background style flips the face color to black and the text, ticks and default line color to white. If you want your own dark theme, remember to change every color that assumed a white page: figure face, axes face, text, ticks, edges and grid.

Python A dark theme for slides

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Pick saturated colors that stay bright on a dark page; the deep blues that work on white nearly vanish. Setting savefig.facecolor as well keeps a saved file dark (Saving Figures covers saving in detail).

Slides versus print

One theme rarely fits every medium. A figure that is readable on a printed page at 6 inches wide is unreadable when projected, because the audience sits far away. Keep a base theme and scale the sizes.

Medium Typical figsize Font size Line width
Print or paper 6 x 4 in 8-10 pt 1-1.5
Web article 8 x 4.5 in 11-12 pt 2
Slides 10 x 5.6 in 16-20 pt 3
Python One chart, two scales

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The slide version is physically larger but, more importantly, its text is large relative to the figure, which is what the back row needs. Whenever you change figsize, think about the font size too: a figure scaled down in a document shrinks its text with it.

Where settings win

When several things set the same property, the most specific one wins:

  1. An explicit argument such as ax.plot(x, y, linewidth=5).
  2. An rc_context block or a call to plt.rcParams[...] = ....
  3. The active style (plt.style.use).
  4. Matplotlib's built-in defaults (your matplotlibrc file, if any, sits between 3 and 4).

That order means a theme gives sensible defaults and you can still break the rule for one chart. To go back to factory settings, call plt.rcdefaults(), or plt.style.use("default") to also reset the style.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between plt.style.use("ggplot") and with plt.style.context("ggplot")?

    style.use modifies the global rcParams until you change them again. style.context applies the style temporarily and restores the previous settings when the block ends.
  2. 2. You set plt.rcParams["lines.linewidth"] = 3 and then call ax.plot(x, y, linewidth=1). What line width is drawn?

    Arguments passed to a call are the most specific setting and always override rcParams and styles.
  3. 3. What does cycler(color=["red", "blue"]) + cycler(linestyle=["-", "--"]) produce?

    Adding cyclers pairs their items one to one, like zip. Multiplying them with * would give every combination.
  4. 4. Why should a custom dark theme set more than the figure background?

    Default text, ticks and spines are dark, so on a dark background they become nearly invisible unless you recolor them too.
  5. 5. A figure will be projected in a lecture hall. Which change helps most?

    Distant viewers need text and lines that are large compared with the whole figure, so raise font.size and lines.linewidth.

Summary

  • A style is a named bundle of rcParams; plt.style.use() applies it globally and plt.style.context() temporarily.
  • plt.rcParams is a dictionary of defaults such as font.size, lines.linewidth and axes.grid.
  • plt.rc_context({...}) changes settings for one block and restores them afterwards.
  • A cycler defines the color, linestyle and marker sequence; + pairs items, * combines them.
  • Keep a house style as one dictionary so every chart looks related, and recolor everything for dark themes.
  • Scale font size, line width and figure size together for print, web and slides.
  • Explicit arguments always beat rcParams, which beat the built-in defaults.

Next: Designing Clear Charts