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
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ Do not commit or push if either fails. Fix issues first.
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.
Place them with `add_axes_inches`, `legend_inches` and `suptitle_inches` from
`mplplots.utils`, 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
Expand Down
46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,52 @@ replaces the major tick locators of linear numeric axes. If you set custom tick
labels on such an axis (for example, the group labels of a grouped bar chart with numeric bar
positions), set them after calling `auto_ticks`.

## Axis lengths in inches

GraphPad Prism sets the length of each axis directly, instead of deriving it from the figure size
and margins. `add_axes_inches` does the same: it places axes at a position and size given in
inches from the figure's lower-left corner, so the x- and y-axes are exactly as long as you ask.
`legend_inches` and `suptitle_inches` place a legend and a figure title in inches too. All three
keep their place when the figure is resized and at any dpi, and because the style does not crop
saved figures, the saved file has exactly the figure's size.

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

from mplplots.utils import add_axes_inches, auto_ticks, legend_inches

plt.style.use("mplplots.styles.GraphPadPrism")

x = np.linspace(0, 10, 50)
fig = plt.figure(figsize=(3, 2.25)) # the saved file is 3 × 2.25 in
ax = add_axes_inches(fig, left=0.5, bottom=0.4, width=2.25, height=1.5) # 2.25 in by 1.5 in axes
ax.plot(x, np.sin(x), label="sin(x)")
ax.plot(x, np.cos(x), label="cos(x)")
auto_ticks(ax, left=0, right=10)
ax.set_xlabel("x")
ax.set_ylabel("y")
legend_inches(ax, 2.75, 1.9, loc="upper right", ncols=2) # upper-right corner at (2.75, 1.9) in
fig.savefig("figure.pdf")
```

- `add_axes_inches(fig, left, bottom, width, height, **kwargs)` adds axes whose x-axis is
`width` and y-axis `height` inches long, meeting at (`left`, `bottom`). Other keyword arguments
go to `fig.add_axes`.
- `legend_inches(ax, x, y, loc="upper left", **kwargs)` places the point of the legend box that
`loc` names at (`x`, `y`): a corner (`"upper left"`), the middle of an edge (`"center left"`),
or `"center"`. Other keyword arguments, such as `ncols` or `title`, go to `ax.legend`.
- `suptitle_inches(fig, t, top=0.1, **kwargs)` adds a centered figure title whose top edge is
`top` inches below the figure's top edge.

With the style's 8 pt text, about 0.5 in to the left of the axes fits the tick labels and a y-axis
label, 0.4 in below fits the tick labels and an x-axis label, and 0.35 in above fits an axes
title. The GraphPadPrism image at the top of this README uses the layout above, plus a title.

The axes keep their position through an axes locator, so `tight_layout`, constrained layout,
`ax.set_position`, and the space `fig.colorbar(..., ax=ax)` takes do not move them. For a
colorbar, add its axes with `add_axes_inches` and pass them as `cax`.

## Gallery

Generated by [`examples/styles_demo.py`](examples/styles_demo.py):
Expand Down
81 changes: 9 additions & 72 deletions examples/_common.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
"""Shared setup for the example scripts: Arial check, round-inch layout and saving.
"""Shared setup for the example scripts: the Arial check and saving in three formats.

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.
Every figure is laid out in round inches with ``mplplots.utils.add_axes_inches``,
``legend_inches`` and ``suptitle_inches``: the figure size, the position and size of
each axes, and the anchors of legends and figure titles are multiples of 0.1, 0.25, 0.5
or 1 in. ``save`` writes each figure 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
from typing import TYPE_CHECKING, Any

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"
Expand All @@ -28,7 +26,8 @@
DPI = 600

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

Expand All @@ -44,68 +43,6 @@ def require_arial() -> None:
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``.

Expand Down
26 changes: 13 additions & 13 deletions examples/palettes_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import matplotlib.pyplot as plt
import numpy as np
from _common import STYLE, add_axes, legend, require_arial, save, suptitle
from _common import STYLE, require_arial, save
from matplotlib.figure import Figure

import mplplots.palettes as palettes
Expand All @@ -17,7 +17,7 @@
REDS,
get_colors,
)
from mplplots.utils import auto_ticks
from mplplots.utils import add_axes_inches, auto_ticks, legend_inches, suptitle_inches

require_arial()
plt.style.use(STYLE)
Expand All @@ -43,7 +43,7 @@ def swatches(
"""
cell_width, cell_height = cell
for row, (name, colors) in enumerate(reversed(list(rows.items()))):
ax = add_axes(
ax = add_axes_inches(
fig, left, bottom + row * (cell_height + gap), len(colors) * cell_width, cell_height
)
for i, c in enumerate(colors):
Expand All @@ -61,12 +61,12 @@ def swatches(
# ---------------------------------------------------------------------------
x = np.linspace(0, 2 * np.pi, 100)
fig = plt.figure(figsize=(4.5, 2.75))
ax = add_axes(fig, 0.5, 0.4, 3, 2)
ax = add_axes_inches(fig, 0.5, 0.4, 3, 2)
for i, color in enumerate(CUSTOM):
ax.plot(x, np.sin(x + i * 0.3), color=color, label=f"Line {i}")
auto_ticks(ax, left=0)
ax.set_title("CUSTOM palette — multi-line plot")
legend(fig, ax, 3.6, 2.4)
legend_inches(ax, 3.6, 2.4)
save(fig, "custom_multiline")

# ---------------------------------------------------------------------------
Expand All @@ -75,15 +75,15 @@ def swatches(
families = {"BLUES": BLUES, "GREENS": GREENS, "REDS": REDS, "PURPLES": PURPLES, "ORANGES": ORANGES}
fig = plt.figure(figsize=(4, 1.9))
swatches(fig, families, left=0.75, bottom=0.1, cell=(0.4, 0.2), gap=0.1)
suptitle(fig, "Colormap-derived families")
suptitle_inches(fig, "Colormap-derived families")
save(fig, "color_families")

# ---------------------------------------------------------------------------
# 3. get_colors() with different colormaps
# ---------------------------------------------------------------------------
fig = plt.figure(figsize=(6, 1.8))
for i, cmap_name in enumerate(["coolwarm", "viridis", "YlGnBu"]):
ax = add_axes(fig, 0.4 + i * 2, 0.2, 1.5, 1.25)
ax = add_axes_inches(fig, 0.4 + i * 2, 0.2, 1.5, 1.25)
colors = get_colors(cmap_name, 6, 0.15, 0.85)
ax.bar(range(len(colors)), [3 + i * 0.5 for i in range(len(colors))], color=colors)
ax.set_title(f'get_colors("{cmap_name}", 6)')
Expand Down Expand Up @@ -130,7 +130,7 @@ def swatches(
cell=(0.3, 0.15),
gap=0.05,
)
suptitle(fig, "All 25 custom-style palettes")
suptitle_inches(fig, "All 25 custom-style palettes")
save(fig, "all_palettes")

# ---------------------------------------------------------------------------
Expand All @@ -139,7 +139,7 @@ def swatches(
rng = np.random.default_rng(42)
fig = plt.figure(figsize=(5.5, 1.7))
for i, name in enumerate(["OCEAN", "ROSE", "FOREST"]):
ax = add_axes(fig, 0.25 + i * 1.75, 0.1, 1.5, 1.25)
ax = add_axes_inches(fig, 0.25 + i * 1.75, 0.1, 1.5, 1.25)
pal = getattr(palettes, name)
for j, c in enumerate(pal):
xs = rng.normal(j, 0.3, 20)
Expand All @@ -155,7 +155,7 @@ def swatches(
# ---------------------------------------------------------------------------
x = np.linspace(0, 4, 80)
fig = plt.figure(figsize=(4.5, 2.5))
ax = add_axes(fig, 0.5, 0.4, 3, 1.75)
ax = add_axes_inches(fig, 0.5, 0.4, 3, 1.75)
spring = palettes.SPRING
base = np.zeros_like(x)
for i in range(6):
Expand All @@ -164,14 +164,14 @@ def swatches(
base += y
auto_ticks(ax, left=0, right=4, bottom=0)
ax.set_title("SPRING palette — stacked area chart")
legend(fig, ax, 3.6, 2.15)
legend_inches(ax, 3.6, 2.15)
save(fig, "spring_area")

# ---------------------------------------------------------------------------
# 7. Pie chart with CANDY palette
# ---------------------------------------------------------------------------
fig = plt.figure(figsize=(2.5, 2.5))
ax = add_axes(fig, 0.25, 0.1, 2, 2)
ax = add_axes_inches(fig, 0.25, 0.1, 2, 2)
candy = palettes.CANDY
sizes = [22, 18, 15, 13, 10, 8, 7, 4, 2, 1]
ax.pie(sizes, colors=candy[:10], startangle=90, wedgeprops={"edgecolor": "white", "linewidth": 1.5})
Expand All @@ -182,7 +182,7 @@ def swatches(
# 8. Horizontal bar chart with DUSK palette
# ---------------------------------------------------------------------------
fig = plt.figure(figsize=(3.5, 3))
ax = add_axes(fig, 0.6, 0.4, 2.6, 2.25)
ax = add_axes_inches(fig, 0.6, 0.4, 2.6, 2.25)
dusk = palettes.DUSK
categories = [f"Item {chr(65 + i)}" for i in range(11)]
values = [45, 38, 35, 30, 28, 24, 20, 18, 14, 10, 6]
Expand Down
22 changes: 11 additions & 11 deletions examples/styles_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

import matplotlib.pyplot as plt
import numpy as np
from _common import STYLE, add_axes, legend, require_arial, save
from _common import STYLE, require_arial, save
from matplotlib import ticker

import mplplots.palettes as palettes
from mplplots.palettes import BLUES, REDS
from mplplots.utils import auto_ticks
from mplplots.utils import add_axes_inches, auto_ticks, legend_inches

require_arial()

Expand All @@ -28,21 +28,21 @@
plt.style.use(STYLE)

fig = plt.figure(figsize=(3, 2.25))
ax = add_axes(fig, 0.5, 0.4, 2.25, 1.5)
ax = add_axes_inches(fig, 0.5, 0.4, 2.25, 1.5)
ax.plot(x, np.sin(x), color=BLUES[4], label="sin(x)")
ax.plot(x, np.cos(x), color=REDS[4], label="cos(x)")
auto_ticks(ax, left=0, right=10)
ax.set_title("GraphPadPrism + auto_ticks")
ax.set_xlabel("x")
ax.set_ylabel("y")
legend(fig, ax, 2.75, 1.9, loc="upper right", ncols=2)
legend_inches(ax, 2.75, 1.9, loc="upper right", ncols=2)
save(fig, "graphpadprism_style")

# ---------------------------------------------------------------------------
# 2. Bar chart with GraphPadPrism
# ---------------------------------------------------------------------------
fig = plt.figure(figsize=(2.75, 2.25))
ax = add_axes(fig, 0.5, 0.4, 2, 1.5)
ax = add_axes_inches(fig, 0.5, 0.4, 2, 1.5)
categories = ["A", "B", "C", "D", "E"]
values = [23, 45, 12, 67, 34]
ax.bar(categories, values, color=BLUES[:5])
Expand All @@ -56,22 +56,22 @@
# 3. Multi-line with GraphPadPrism + OCEAN palette
# ---------------------------------------------------------------------------
fig = plt.figure(figsize=(4, 2.25))
ax = add_axes(fig, 0.5, 0.4, 2.5, 1.5)
ax = add_axes_inches(fig, 0.5, 0.4, 2.5, 1.5)
ocean = palettes.OCEAN
for i in range(6):
ax.plot(x, np.sin(x + i * 0.4) * (1 - i * 0.1), color=ocean[i], label=f"Wave {i}")
auto_ticks(ax, left=0, right=10)
ax.set_xlabel("Time")
ax.set_ylabel("Amplitude")
ax.set_title("OCEAN palette + GraphPadPrism")
legend(fig, ax, 3.1, 1.9)
legend_inches(ax, 3.1, 1.9)
save(fig, "graphpadprism_ocean")

# ---------------------------------------------------------------------------
# 4. Grouped bar chart with GraphPadPrism + AUTUMN palette
# ---------------------------------------------------------------------------
fig = plt.figure(figsize=(4, 2.25))
ax = add_axes(fig, 0.5, 0.4, 2.5, 1.5)
ax = add_axes_inches(fig, 0.5, 0.4, 2.5, 1.5)
autumn = palettes.AUTUMN
groups = ["Q1", "Q2", "Q3", "Q4"]
x_pos = np.arange(len(groups))
Expand All @@ -87,14 +87,14 @@
ax.set_xlim(x_pos[0] + width - 0.5, x_pos[-1] + width + 0.5)
ax.set_ylabel("Value")
ax.set_title("AUTUMN palette — grouped bar chart")
legend(fig, ax, 3.1, 1.9)
legend_inches(ax, 3.1, 1.9)
save(fig, "graphpadprism_grouped_bar")

# ---------------------------------------------------------------------------
# 5. Scatter with error bars + GraphPadPrism + CORAL palette
# ---------------------------------------------------------------------------
fig = plt.figure(figsize=(4, 2.25))
ax = add_axes(fig, 0.5, 0.4, 2.5, 1.5)
ax = add_axes_inches(fig, 0.5, 0.4, 2.5, 1.5)
coral = palettes.CORAL
rng = np.random.default_rng(7)
for i in range(5):
Expand All @@ -115,7 +115,7 @@
ax.set_xlabel("X measure")
ax.set_ylabel("Y measure")
ax.set_title("CORAL palette — error bars")
legend(fig, ax, 3.1, 1.9)
legend_inches(ax, 3.1, 1.9)
save(fig, "graphpadprism_errorbar")

print("All style examples saved to examples/")
Loading
Loading