# Dark Mode Charts in Matplotlib

> Turn on dark mode in Matplotlib with plt.style.use("dark_background"), build a softer dark theme with rcParams, and save light and dark versions of a chart.

Source: https://www.pythoncharts.com/matplotlib/matplotlib-dark-mode/ | Published: 2026-11-27 | Author: Alex Scott | Category: Matplotlib | Tags: matplotlib, dark mode, dark_background, style sheets, rcparams, colors

Matplotlib's built-in dark mode is `plt.style.use("dark_background")`. It sets a black background with white text and brighter line colors. For a softer dark gray that matches a dashboard or website, override a handful of `rcParams`.

## Quick Example

```python
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(14)
week = np.arange(1, 27)
signups = {
    "Free": 200 + np.cumsum(rng.normal(9, 14, 26)),
    "Pro": 120 + np.cumsum(rng.normal(6, 9, 26)),
    "Team": 60 + np.cumsum(rng.normal(3, 6, 26)),
}

with plt.style.context("dark_background"):
    fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
    for plan, values in signups.items():
        ax.plot(week, values, linewidth=2.5, label=plan)
    ax.set_title("Weekly signups by plan")
    ax.set_xlabel("Week")
    ax.legend()
    plt.show()
```

![Line chart of weekly signups for three plans on a black background with white text](https://www.pythoncharts.com/matplotlib/matplotlib-dark-mode/images/dark-mode-quick-example.png)

`plt.style.context()` applies the style only inside the `with` block. To switch every chart in a script or notebook, call `plt.style.use("dark_background")` once, before creating any figures. `plt.style.use("default")` switches back.

## A Softer Dark Theme

Pure black with pure white text is high contrast and can look harsh next to a dark gray interface. Put your own colors in a dictionary and pass it after the built-in style:

```python
from cycler import cycler

BACKGROUND = "#161b22"
TEXT = "#c9d1d9"
MUTED = "#30363d"

dark_theme = {
    "figure.facecolor": BACKGROUND,
    "axes.facecolor": BACKGROUND,
    "axes.edgecolor": MUTED,
    "axes.labelcolor": TEXT,
    "text.color": TEXT,
    "xtick.color": TEXT,
    "ytick.color": TEXT,
    "xtick.major.size": 0,
    "ytick.major.size": 0,
    "axes.grid": True,
    "axes.axisbelow": True,
    "grid.color": MUTED,
    "axes.spines.top": False,
    "axes.spines.right": False,
    "axes.spines.left": False,
    "legend.frameon": False,
    "axes.prop_cycle": cycler(color=["#58a6ff", "#f78166", "#56d364", "#d2a8ff", "#e3b341"]),
}

def signup_chart():
    fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
    for plan, values in signups.items():
        ax.plot(week, values, linewidth=2.5, label=plan)
    ax.set_title("Weekly signups by plan", loc="left", fontsize=15)
    ax.set_xlabel("Week")
    ax.legend(ncols=3)
    return fig

with plt.style.context(["dark_background", dark_theme]):
    signup_chart()
    plt.show()
```

![The signups chart on a dark blue-gray background with soft gray text, faint gridlines and pastel lines](https://www.pythoncharts.com/matplotlib/matplotlib-dark-mode/images/dark-mode-custom-theme.png)

Starting from `dark_background` covers settings you might forget, such as box plot lines and legend text.

## Keep the Theme in a File

To reuse the theme across projects, write it to a `.mplstyle` file and pass the path to `plt.style.use()`. Colors in these files are written without `#`, because `#` starts a comment:

```python
from pathlib import Path

Path("midnight.mplstyle").write_text("""
figure.facecolor: 161b22
axes.facecolor:   161b22
axes.labelcolor:  c9d1d9
text.color:       c9d1d9
xtick.color:      c9d1d9
ytick.color:      c9d1d9
axes.edgecolor:   30363d
""")

with plt.style.context(["dark_background", "midnight.mplstyle"]):
    signup_chart()
    plt.close()
```

[rcParams and global defaults](https://www.pythoncharts.com/matplotlib/matplotlib-rcparams-defaults/) explains how to install a style file so you can load it by name.

## Save Light and Dark Versions

Because the chart is built inside a function, the same code can produce both:

```python
themes = {"light": "default", "dark": ["dark_background", dark_theme]}

for name, style in themes.items():
    with plt.style.context(style):
        fig = signup_chart()
        fig.savefig(f"signups-{name}.png", dpi=150)
        plt.close(fig)
```

Call `savefig()` inside the `with` block, so any `savefig.*` settings in the style apply. The background color is saved as drawn: `savefig.facecolor` defaults to `"auto"`, which uses the figure's color.

On a web page, an HTML `<picture>` element can then show whichever file matches the visitor's setting:

```html
<picture>
  <source srcset="signups-dark.png" media="(prefers-color-scheme: dark)">
  ![Weekly signups by plan](signups-light.png)
</picture>
```

## Transparent Background for Dark Pages

To let the page color show through, save with `transparent=True`. The text stays light, so the image only reads well on a dark surface:

```python
with plt.style.context(["dark_background", dark_theme]):
    fig = signup_chart()
    fig.savefig("signups-transparent.png", dpi=150, transparent=True)
    plt.close(fig)
```

See [transparent backgrounds](https://www.pythoncharts.com/matplotlib/matplotlib-transparent-background-png-export/) for more control.

## Colors That Work on Dark Backgrounds

- Dark colors such as navy or maroon disappear. Use lighter, slightly desaturated ones.
- Any color you hard-code stays the same in both themes. `color="black"` is invisible in dark mode; use `"C0"`, `"C1"` for cycle colors, or read `plt.rcParams["text.color"]` for neutral lines and labels.
- For heatmaps, `"viridis"`, `"magma"`, and `"inferno"` start dark, so low values fade into the background. That's usually what you want.

```python
rng = np.random.default_rng(5)
usage = rng.gamma(30, 1 / 30, (7, 24)) * (2 + 12 * np.exp(-((np.arange(24) - 14) / 4) ** 2))

with plt.style.context(["dark_background", dark_theme, {"axes.grid": False}]):
    fig, ax = plt.subplots(figsize=(8, 3.5), layout="constrained")
    image = ax.imshow(usage, cmap="magma", aspect="auto")
    ax.set_yticks(range(7), ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
    ax.set_xlabel("Hour of day")
    # Start of office hours, drawn in the theme's text color
    ax.axvline(8.5, color=plt.rcParams["text.color"], linestyle="--", linewidth=1)
    fig.colorbar(image, label="Requests (thousands)")
    plt.show()
```

![Dark-themed heatmap of requests by weekday and hour using the magma colormap, brightest in the early afternoon, with a dashed line marking the start of office hours](https://www.pythoncharts.com/matplotlib/matplotlib-dark-mode/images/dark-mode-heatmap.png)

## Similar Topics

- [Built-In Style Sheets in Matplotlib](https://www.pythoncharts.com/matplotlib/matplotlib-built-in-style-sheets/)
- [rcParams and Global Defaults](https://www.pythoncharts.com/matplotlib/matplotlib-rcparams-defaults/)
- [Transparent Backgrounds](https://www.pythoncharts.com/matplotlib/matplotlib-transparent-background-png-export/)
