Skip to content
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
3 changes: 3 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
hooks:
# The example SVGs are written by Matplotlib and must stay byte for byte as rendered.
- id: trailing-whitespace
exclude: ^examples/.*\.svg$
- id: end-of-file-fixer
exclude: ^examples/.*\.svg$
- id: check-yaml
- id: check-toml
- id: check-added-large-files
Expand Down
16 changes: 16 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,19 @@ Do not commit or push if either fails. Fix issues first.
(`pdf.fonttype` and `ps.fonttype` 42), stores SVG text as paths, and sets no figure size.
- A change to the style goes together with the "What the style changes" table in `README.md` and
the assertions in `tests/test_styles.py`.

## Rendering Figures

- The README images come from `examples/styles_demo.py` and `examples/palettes_demo.py`. All of
them use the GraphPadPrism style except `default_style`, which shows Matplotlib's defaults.
- Lay figures out in round inches: the figure size, each axes' position and size (the axis
lengths), and the anchors of legends and figure titles are multiples of 0.1, 0.25, 0.5 or 1 in.
Place them with `add_axes`, `legend` and `suptitle` from `examples/_common.py`, not with
`tight_layout`, `subplots_adjust` or a tight bounding box.
- Keep the style's text: pass no `fontsize` or `fontweight`.
- Render every figure in three formats with `save()` from `examples/_common.py`: PNG at 600 dpi,
SVG and PDF, side by side in `examples/`, uncropped and without timestamps, so rerunning an
unchanged script reproduces the files byte for byte.
- Rendering needs Arial installed; the scripts exit without it. After changing the style or a
script, rerun both scripts and commit all three formats. In `README.md`, show each image at
100 pixels per inch of figure width.
47 changes: 24 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ palettes, and a few helpers for publication-quality scientific figures.
</tr>
<tr>
<td><img src="examples/default_style.png" alt="Sine and cosine plotted with Matplotlib's default style" width="400"></td>
<td><img src="examples/graphpadprism_style.png" alt="The same plot with the GraphPad Prism style: bold text, no top or right spines, minor ticks" width="400"></td>
<td><img src="examples/graphpadprism_style.png" alt="The same plot with the GraphPad Prism style: Arial 8 pt text, no top or right spines, minor ticks" width="400"></td>
</tr>
</table>

Expand Down Expand Up @@ -154,15 +154,15 @@ slice it and pass it anywhere Matplotlib or seaborn accepts colors.
<details>
<summary>Show all 25 palettes</summary>

<img src="examples/all_palettes.png" alt="Swatches of all 25 hand-picked palettes" width="700">
<img src="examples/all_palettes.png" alt="Swatches of all 25 hand-picked palettes" width="425">

</details>

The colormap families `BLUES`, `GREENS`, `REDS`, `PURPLES`, `ORANGES`, and `GREYS` each have 8
shades running from light to dark. Their colors are sampled from the matching Matplotlib colormap
between 0.3 and 0.8 (0.25 and 0.75 for `GREYS`), which skips near-white and near-black.

<img src="examples/color_families.png" alt="Swatches of the colormap-derived color families" width="600">
<img src="examples/color_families.png" alt="Swatches of the colormap-derived color families" width="400">

### Using a palette

Expand Down Expand Up @@ -227,7 +227,7 @@ get_colors("viridis", 5, start=0.8, end=0.2) # or sample in reverse order
`n` must be at least 1, and `start` and `end` must be between 0 and 1. Otherwise, and for an
unknown colormap name, `get_colors` raises `ValueError`.

<img src="examples/get_colors_demo.png" alt="Bar charts colored with get_colors from coolwarm, viridis, and YlGnBu" width="700">
<img src="examples/get_colors_demo.png" alt="Bar charts colored with get_colors from coolwarm, viridis, and YlGnBu" width="600">

## Ticks: `auto_ticks`

Expand Down Expand Up @@ -281,16 +281,16 @@ Generated by [`examples/styles_demo.py`](examples/styles_demo.py):

<table>
<tr>
<td><img src="examples/graphpadprism_bar.png" alt="Bar chart" width="380"></td>
<td><img src="examples/graphpadprism_ocean.png" alt="Multi-line plot" width="380"></td>
<td><img src="examples/graphpadprism_bar.png" alt="Bar chart" width="275"></td>
<td><img src="examples/graphpadprism_ocean.png" alt="Multi-line plot" width="400"></td>
</tr>
<tr>
<td>Bar chart colored with <code>BLUES[:5]</code></td>
<td>Phase-shifted waves in <code>OCEAN</code></td>
</tr>
<tr>
<td><img src="examples/graphpadprism_grouped_bar.png" alt="Grouped bar chart" width="380"></td>
<td><img src="examples/graphpadprism_errorbar.png" alt="Error bar plot" width="380"></td>
<td><img src="examples/graphpadprism_grouped_bar.png" alt="Grouped bar chart" width="400"></td>
<td><img src="examples/graphpadprism_errorbar.png" alt="Error bar plot" width="400"></td>
</tr>
<tr>
<td>Grouped bar chart in <code>AUTUMN</code></td>
Expand All @@ -303,42 +303,43 @@ palette swatches and the `get_colors` figure above:

<table>
<tr>
<td><img src="examples/custom_multiline.png" alt="Multi-line plot" width="380"></td>
<td><img src="examples/scatter_comparison.png" alt="Scatter plots" width="380"></td>
<td><img src="examples/custom_multiline.png" alt="Multi-line plot" width="450"></td>
<td><img src="examples/dusk_hbar.png" alt="Horizontal bar chart" width="350"></td>
</tr>
<tr>
<td>All 11 <code>CUSTOM</code> colors as lines</td>
<td>Scatter plots in <code>OCEAN</code>, <code>ROSE</code>, and <code>FOREST</code></td>
<td>Horizontal bar chart in <code>DUSK</code></td>
</tr>
<tr>
<td><img src="examples/spring_area.png" alt="Stacked area chart" width="380"></td>
<td><img src="examples/dusk_hbar.png" alt="Horizontal bar chart" width="380"></td>
<td><img src="examples/spring_area.png" alt="Stacked area chart" width="450"></td>
<td><img src="examples/candy_pie.png" alt="Pie chart" width="250"></td>
</tr>
<tr>
<td>Stacked area chart in <code>SPRING</code></td>
<td>Horizontal bar chart in <code>DUSK</code></td>
<td>Pie chart in <code>CANDY</code></td>
</tr>
<tr>
<td><img src="examples/candy_pie.png" alt="Pie chart" width="300"></td>
<td></td>
<td colspan="2"><img src="examples/scatter_comparison.png" alt="Scatter plots" width="550"></td>
</tr>
<tr>
<td>Pie chart in <code>CANDY</code></td>
<td></td>
<td colspan="2">Scatter plots in <code>OCEAN</code>, <code>ROSE</code>, and <code>FOREST</code></td>
</tr>
</table>

To regenerate the images, run the scripts from any directory. The images are written to
`examples/`, next to the scripts:
To regenerate the images, run the scripts from any directory. Each figure is written to
`examples/`, next to the scripts, as PNG (600 dpi), SVG, and PDF:

```bash
python examples/styles_demo.py
python examples/palettes_demo.py
```

All text in the images is set in Arial, except the Matplotlib-defaults comparison at the top of
this README. The scripts need Arial (regular and bold) installed and exit with an error without it,
instead of writing images in a fallback font.
Every image uses the GraphPadPrism style, except the Matplotlib-defaults comparison at the top of
this README. Each figure is laid out in round inches (its size, the position and size of each axes,
and the anchors of legends and titles), and the files are saved uncropped, so they keep that size.
Apart from the comparison at the top, the README shows the images at 100 pixels per inch, so the
8 pt text appears the same size in each. The scripts need Arial installed and exit with an error
without it, instead of writing images in a fallback font.

## Development

Expand Down
119 changes: 119 additions & 0 deletions examples/_common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""Shared setup for the example scripts: Arial check, round-inch layout and saving.

Every figure is laid out in inches from its lower-left corner. The figure size, the
position and size of each axes, and the anchors of legends and figure titles are round
values: multiples of 0.1, 0.25, 0.5 or 1 in. Figures are saved uncropped, so the files
keep that size, as PNG (600 dpi), SVG and PDF.
"""

from __future__ import annotations

import sys
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal

import matplotlib.pyplot as plt
from matplotlib import font_manager

if TYPE_CHECKING:
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from matplotlib.legend import Legend
from matplotlib.text import Text
from matplotlib.typing import RcKeyType # Matplotlib 3.10+

STYLE = "mplplots.styles.GraphPadPrism"
OUT = Path(__file__).resolve().parent
FORMATS = ("png", "svg", "pdf")
DPI = 600

# Without a fixed date and SVG id salt, every run would write different SVG and PDF files
# for the same figure.
_METADATA: dict[str, dict[str, Any]] = {"svg": {"Date": None}, "pdf": {"CreationDate": None}}
_SAVE_RC: dict[RcKeyType, Any] = {"savefig.bbox": "standard", "svg.hashsalt": "mplplots"}


def require_arial() -> None:
"""Exit unless Arial is installed.

Without Arial the style silently falls back to a look-alike font (Liberation Sans,
...), so the README images are never written in anything but Arial.
"""
faces = {(f.name, f.style, f.weight) for f in font_manager.fontManager.ttflist}
if ("Arial", "normal", 400) not in faces:
sys.exit("Arial is not installed; install it to regenerate the images.")


def add_axes(fig: Figure, left: float, bottom: float, width: float, height: float) -> Axes:
"""Add axes of width x height inches whose lower-left corner is at (left, bottom).

Args:
fig: The figure to add the axes to.
left: Distance from the figure's left edge to the axes, in inches.
bottom: Distance from the figure's bottom edge to the axes, in inches.
width: Width of the axes (the x-axis length), in inches.
height: Height of the axes (the y-axis length), in inches.

Returns:
The new axes.
"""
fig_width, fig_height = fig.get_size_inches()
rect = (left / fig_width, bottom / fig_height, width / fig_width, height / fig_height)
return fig.add_axes(rect)


def legend(
fig: Figure,
ax: Axes,
x: float,
y: float,
loc: Literal["upper left", "upper right", "lower left", "lower right"] = "upper left",
**kwargs: Any,
) -> Legend:
"""Add a legend for ax with its loc corner at (x, y) inches on the figure.

Args:
fig: The figure that holds ax.
ax: The axes whose labelled artists the legend lists.
x: Distance from the figure's left edge to the legend's loc corner, in inches.
y: Distance from the figure's bottom edge to the legend's loc corner, in inches.
loc: Which corner of the legend sits at (x, y).
**kwargs: Passed on to ``ax.legend``, e.g. ``ncols``.

Returns:
The new legend.
"""
return ax.legend(
loc=loc,
bbox_to_anchor=(x, y),
bbox_transform=fig.dpi_scale_trans,
borderaxespad=0,
**kwargs,
)


def suptitle(fig: Figure, text: str, top: float = 0.1) -> Text:
"""Center a figure title with its top edge top inches below the figure's top edge.

Args:
fig: The figure to title.
text: The title.
top: Distance from the figure's top edge to the title's top edge, in inches.

Returns:
The title text.
"""
return fig.suptitle(text, y=1 - top / fig.get_size_inches()[1], va="top")


def save(fig: Figure, name: str) -> None:
"""Save fig uncropped as ``examples/<name>.png`` (600 dpi), ``.svg`` and ``.pdf``.

Args:
fig: The figure to save; it is closed afterwards.
name: The file name without extension.
"""
with plt.rc_context(_SAVE_RC):
for fmt in FORMATS:
fig.savefig(OUT / f"{name}.{fmt}", dpi=DPI, metadata=_METADATA.get(fmt))
plt.close(fig)
Binary file added examples/all_palettes.pdf
Binary file not shown.
Binary file modified examples/all_palettes.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading