From 4cc15d5707096681573f89edd009284307d699d3 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Tue, 3 Nov 2026 14:05:18 +1000 Subject: [PATCH 01/11] add treemaps --- docs/examples/plot_types/14_treemap.py | 38 ++++ ultraplot/axes/plot.py | 102 +++++++++ ultraplot/axes/plot_types/treemap.py | 296 +++++++++++++++++++++++++ ultraplot/tests/test_treemap.py | 187 ++++++++++++++++ 4 files changed, 623 insertions(+) create mode 100644 docs/examples/plot_types/14_treemap.py create mode 100644 ultraplot/axes/plot_types/treemap.py create mode 100644 ultraplot/tests/test_treemap.py diff --git a/docs/examples/plot_types/14_treemap.py b/docs/examples/plot_types/14_treemap.py new file mode 100644 index 000000000..76eb040ae --- /dev/null +++ b/docs/examples/plot_types/14_treemap.py @@ -0,0 +1,38 @@ +""" +Treemaps +======== + +``PlotAxes.treemap`` represents each value by a rectangle's area. Nested +mappings group related categories inside parent rectangles. Both examples use +synthetic data. Layout and rendering require only UltraPlot's core dependencies. +""" + +import ultraplot as uplt + +fig, axs = uplt.subplots(ncols=2, refwidth=4.2, refaspect=1, share=False) + +axs[0].treemap( + {"Solar": 36, "Wind": 28, "Hydro": 18, "Nuclear": 12, "Other": 6}, + color=["#3c8d87", "#5286b0", "#69a4b7", "#af8a55", "#959baa"], + show_values=True, + value_format="{:.0f}%", + pad=0.012, + text_kw={"fontsize": 11}, +) +axs[0].format(title="Flat categories") + +axs[1].treemap( + { + "Research": {"Fieldwork": 24, "Equipment": 16, "Data": 10}, + "People": {"Staff": 20, "Training": 10}, + "Operations": {"Travel": 12, "Services": 8}, + }, + show_values=True, + value_format="{:.0f}", + pad=0.012, + group_pad=0.018, + text_kw={"fontsize": 10}, +) +axs[1].format(title="Nested categories") +axs.format(suptitle="Treemaps · area shows value") +fig.show() diff --git a/ultraplot/axes/plot.py b/ultraplot/axes/plot.py index 405d027e0..9087abd13 100644 --- a/ultraplot/axes/plot.py +++ b/ultraplot/axes/plot.py @@ -6749,6 +6749,108 @@ def violinploth(self, *args, **kwargs): kwargs = _parse_vert(default_vert=False, **kwargs) return self._apply_violinplot(*args, **kwargs) + def treemap( + self, + sizes, + labels=None, + *, + data=None, + color=None, + cmap=None, + norm=None, + vmin=None, + vmax=None, + rect=(0, 0, 1, 1), + pad=0.008, + group_pad=0.018, + group_labels=True, + show_values=False, + value_format="{:g}", + text_kw=None, + group_kw=None, + **kwargs, + ): + """Draw an area-proportional treemap of flat or hierarchical data. + + Requires Cartesian axes with linear scales. + + Parameters + ---------- + sizes : sequence of float, mapping, or pandas.Series + Nonnegative tile sizes. Zero-sized leaves are omitted. A mapping + supplies labels from its keys; nested mappings define groups, whose + areas are proportional to the sum of their descendants. A Series + supplies labels from its index. Values must be finite, with at + least one positive value in each group. No extra package is needed. + labels : sequence of str, optional + Labels for a flat sequence, in input order. + data : mapping, optional + Look up string ``sizes`` and ``labels`` arguments in this object. + color : color or sequence of colors, optional + A single color or one color per nonzero leaf in input order. + By default, top-level categories use the current cycle, and leaves + within a group share shades of the group's color. + cmap : colormap, optional + Color leaves by size. Mutually exclusive with ``color``. + norm : matplotlib.colors.Normalize, optional + Normalization for ``cmap``. Cannot be combined with vmin/vmax. + vmin, vmax : float, optional + Colormap bounds when ``norm`` is omitted. + rect : tuple of float, default: (0, 0, 1, 1) + Bounding rectangle as (x, y, width, height), in data coordinates. + The axes uses equal scaling so tile areas are not distorted. + pad, group_pad : float, default: 0.008, 0.018 + Gaps between leaf tiles and group frames in data coordinates. + Padding and group headings reduce the visible area of each tile; + use zero padding and ``group_labels=False`` for exact area ratios. + group_labels : bool, default: True + Reserve a header for each group name. + show_values : bool, default: False + Add the numeric size below each leaf label. + value_format : str or callable, default: '{:g}' + Format string or function used by ``show_values``. + text_kw, group_kw : dict, optional + Leaf text properties and group rectangle properties. Text is + clipped to its tile. Other keyword arguments style leaf rectangles. + + Returns + ------- + dict + ``patches``, ``texts``, ``paths``, and ``values`` follow input leaf + order, omitting zeros. ``texts`` includes None for unlabeled tiles. + ``groups`` and ``group_texts`` contain group artists. ``mappable`` + is a ScalarMappable for a colorbar when using ``cmap``, else None. + + Examples + -------- + >>> fig, ax = uplt.subplots() + >>> artists = ax.treemap({'A': 6, 'B': 3, 'C': 1}, show_values=True) + >>> artists = ax.treemap({'Group': {'A': 6, 'B': 3}, 'Other': 1}) + """ + from .plot_types.treemap import treemap + + if data is not None: + sizes, labels = inputs._from_data(data, sizes, labels) + return treemap( + self, + sizes, + labels, + color=color, + cmap=cmap, + norm=norm, + vmin=vmin, + vmax=vmax, + rect=rect, + pad=pad, + group_pad=group_pad, + group_labels=group_labels, + show_values=show_values, + value_format=value_format, + text_kw=text_kw, + group_kw=group_kw, + **kwargs, + ) + def raincloud( self, dataset: Any = None, diff --git a/ultraplot/axes/plot_types/treemap.py b/ultraplot/axes/plot_types/treemap.py new file mode 100644 index 000000000..20832c9ad --- /dev/null +++ b/ultraplot/axes/plot_types/treemap.py @@ -0,0 +1,296 @@ +"""Area-proportional, squarified treemaps using native Matplotlib artists.""" + +from collections.abc import Mapping +from dataclasses import dataclass +import math + +import matplotlib.cm as mcm +import matplotlib.colors as mcolors +from matplotlib.patches import Rectangle +import numpy as np + +from ... import constructor +from ...config import rc +from ...internals import _pop_props + + +@dataclass +class _Node: + label: str + value: float + path: tuple + children: tuple = () + + +def _nodes(sizes, labels=None, path=()): + """Validate the complete hierarchy before adding any artists.""" + if isinstance(sizes, Mapping) or ( + getattr(sizes, "ndim", None) == 1 and hasattr(sizes, "items") + ): + if labels is not None: + raise ValueError("Mapping and Series inputs already supply their labels.") + result = [] + for key, value in sizes.items(): + child_path = (*path, key) + if isinstance(value, Mapping): + children = _nodes(value, path=child_path) + total = math.fsum(child.value for child in children) + result.append(_Node(str(key), total, child_path, tuple(children))) + else: + result.append(_Node(str(key), _value(value), child_path)) + else: + try: + values = np.ma.asarray(sizes, dtype=float).filled(np.nan) + except (TypeError, ValueError) as exc: + raise ValueError( + "sizes must be a one-dimensional numeric sequence." + ) from exc + if values.ndim != 1: + raise ValueError("sizes must be a one-dimensional numeric sequence.") + if labels is None: + labels = [""] * len(values) + elif isinstance(labels, str) or len(labels) != len(values): + raise ValueError("labels must have the same length as sizes.") + result = [ + _Node(str(label), _value(value), (index,)) + for index, (value, label) in enumerate(zip(values, labels)) + ] + if not result or not any(node.value > 0 for node in result): + raise ValueError("sizes must contain at least one positive value.") + return result + + +def _value(value): + try: + value = float(value) + except (TypeError, ValueError) as exc: + raise ValueError("sizes must contain finite, nonnegative numbers.") from exc + if not math.isfinite(value) or value < 0: + raise ValueError("sizes must contain finite, nonnegative numbers.") + return value + + +def _squarify(nodes, rect): + """Tile a rectangle with compact strips, retaining each node's identity.""" + x, y, width, height = rect + ordered = sorted((node for node in nodes if node.value > 0), key=lambda n: -n.value) + scale = max(node.value for node in ordered) + weights = [node.value / scale for node in ordered] + total = math.fsum(weights) + areas = [weight / total * width * height for weight in weights] + result = [] + + def worst(row, side): + total = math.fsum(area for _, area in row) + smallest = min(area for _, area in row) + largest = max(area for _, area in row) + return max( + side * side * largest / total**2, total**2 / (side * side * smallest) + ) + + def place(row, x, y, width, height): + area = math.fsum(size for _, size in row) + if width >= height: + strip = area / height + offset = y + for node, size in row: + length = size / strip + result.append((node, (x, offset, strip, length))) + offset += length + return x + strip, y, max(0, width - strip), height + strip = area / width + offset = x + for node, size in row: + length = size / strip + result.append((node, (offset, y, length, strip))) + offset += length + return x, y + strip, width, max(0, height - strip) + + row = [] + for node, area in zip(ordered, areas): + candidate = [*row, (node, area)] + if row and worst(candidate, min(width, height)) > worst( + row, min(width, height) + ): + x, y, width, height = place(row, x, y, width, height) + row = [] + row.append((node, area)) + if row: + place(row, x, y, width, height) + return result + + +def _inset(rect, pad): + x, y, width, height = rect + inset = min(pad / 2, width * 0.2, height * 0.2) + return x + inset, y + inset, width - 2 * inset, height - 2 * inset + + +def treemap( + ax, + sizes, + labels=None, + *, + color=None, + cmap=None, + norm=None, + vmin=None, + vmax=None, + rect=(0, 0, 1, 1), + pad=0.008, + group_pad=0.018, + group_labels=True, + show_values=False, + value_format="{:g}", + text_kw=None, + group_kw=None, + **kwargs, +): + if not ax.transData.is_affine: + raise ValueError("treemap requires Cartesian axes with linear scales.") + nodes = _nodes(sizes, labels) + rect = np.asarray(rect, dtype=float) + if rect.shape != (4,) or not np.all(np.isfinite(rect)) or np.any(rect[2:] <= 0): + raise ValueError("rect must be (x, y, width, height) with positive dimensions.") + if not np.isfinite(pad) or pad < 0 or not np.isfinite(group_pad) or group_pad < 0: + raise ValueError("pad and group_pad must be finite and nonnegative.") + if color is not None and cmap is not None: + raise ValueError("Use either color or cmap, not both.") + if not callable(value_format) and not isinstance(value_format, str): + raise ValueError("value_format must be a format string or callable.") + + leaves = [] + + def collect(branch): + for node in branch: + if node.children: + collect(node.children) + elif node.value > 0: + leaves.append(node) + + collect(nodes) + values = np.array([node.value for node in leaves]) + mappable = None + colors = {} + if cmap is not None: + if norm is None: + norm = mcolors.Normalize(vmin=vmin, vmax=vmax) + elif vmin is not None or vmax is not None: + raise ValueError("vmin/vmax cannot be combined with an explicit norm.") + mappable = mcm.ScalarMappable(norm=norm, cmap=constructor.Colormap(cmap)) + mappable.set_array(values) + mappable.autoscale_None() + colors = { + id(node): rgba for node, rgba in zip(leaves, mappable.to_rgba(values)) + } + elif color is not None: + rgba = mcolors.to_rgba_array(color) + if len(rgba) not in (1, len(leaves)): + raise ValueError( + "color must be a single color or one color per nonzero leaf." + ) + colors = {id(node): rgba[i % len(rgba)] for i, node in enumerate(leaves)} + elif norm is not None or vmin is not None or vmax is not None: + raise ValueError("norm, vmin, and vmax require cmap.") + cycle = constructor.Cycle(rc["cycle"]).by_key()["color"] + + style = dict(kwargs) + style.update(_pop_props(style, "patch")) + style.setdefault("edgecolor", "white") + style.setdefault("linewidth", 0.6) + parent_style = dict(group_kw or {}) + parent_style.update(_pop_props(parent_style, "patch")) + parent_style.setdefault("edgecolor", "white") + parent_style.setdefault("linewidth", 1.2) + text_style = dict(text_kw or {}) + text_style.setdefault("fontsize", 9) + text_style.setdefault("ha", "center") + text_style.setdefault("va", "center") + text_style.setdefault("clip_on", True) + + # Format all values before drawing so a bad formatter leaves the axes untouched. + formatted = {} + if show_values: + for node in leaves: + formatted[id(node)] = str( + value_format(node.value) + if callable(value_format) + else value_format.format(node.value) + ) + + result = { + "patches": [], + "texts": [], + "groups": [], + "group_texts": [], + "paths": [], + "values": [], + "mappable": mappable, + } + drawn = {} + + def draw(branch, bounds, base_color=None): + for index, (node, box) in enumerate(_squarify(branch, bounds)): + hue = base_color if base_color is not None else cycle[index % len(cycle)] + if node.children: + box = _inset(box, group_pad) + x, y, width, height = box + group_style = {"facecolor": hue, "alpha": 0.12, **parent_style} + patch = Rectangle((x, y), width, height, **group_style) + ax.add_patch(patch) + result["groups"].append(patch) + inner = _inset(box, group_pad) + header = min(0.05 * rect[3], inner[3] * 0.18) if group_labels else 0 + if group_labels: + label = ax.text( + inner[0], + inner[1] + inner[3] - header / 2, + node.label, + fontsize=10, + fontweight="bold", + ha="left", + va="center", + clip_on=True, + ) + label.set_clip_path(patch) + result["group_texts"].append(label) + draw(node.children, (*inner[:3], inner[3] - header), hue) + else: + x, y, width, height = _inset(box, pad) + rgba = colors.get(id(node)) + if rgba is None: + # Related leaves share a hue, with gentle categorical shades. + rgb = np.array(mcolors.to_rgb(hue)) + blend = 0.10 + 0.12 * (index % 4) if base_color is not None else 0 + rgba = rgb * (1 - blend) + blend + patch = Rectangle((x, y), width, height, **{"facecolor": rgba, **style}) + ax.add_patch(patch) + text = node.label + if show_values: + text = "\n".join(filter(None, [text, formatted[id(node)]])) + artist = None + if text: + luminance = np.dot( + patch.get_facecolor()[:3], [0.2126, 0.7152, 0.0722] + ) + options = { + "color": "#18212b" if luminance > 0.5 else "white", + **text_style, + } + artist = ax.text(x + width / 2, y + height / 2, text, **options) + artist.set_clip_path(patch) + drawn[id(node)] = patch, artist + + draw(nodes, rect) + # Public results retain input order even though the layout sorts by size. + for node in leaves: + patch, text = drawn[id(node)] + result["patches"].append(patch) + result["texts"].append(text) + result["paths"].append(node.path) + result["values"].append(node.value) + ax.set_xlim(rect[0], rect[0] + rect[2]) + ax.set_ylim(rect[1], rect[1] + rect[3]) + ax.set_aspect("equal", adjustable="box") + ax.set_axis_off() + return result diff --git a/ultraplot/tests/test_treemap.py b/ultraplot/tests/test_treemap.py new file mode 100644 index 000000000..d2b549d9c --- /dev/null +++ b/ultraplot/tests/test_treemap.py @@ -0,0 +1,187 @@ +"""Treemap area conservation, hierarchy, and public plotting behavior.""" + +import numpy as np +import pandas as pd +import pytest +from matplotlib.colors import Normalize, to_rgba + +import ultraplot as uplt + + +def _assert_tiling(patches, bounds): + x, y, width, height = bounds + for i, patch in enumerate(patches): + left, bottom = patch.get_xy() + assert left >= x - 1e-12 + assert bottom >= y - 1e-12 + assert left + patch.get_width() <= x + width + 1e-12 + assert bottom + patch.get_height() <= y + height + 1e-12 + for other in patches[i + 1 :]: + dx = min(left + patch.get_width(), other.get_x() + other.get_width()) - max( + left, other.get_x() + ) + dy = min( + bottom + patch.get_height(), other.get_y() + other.get_height() + ) - max(bottom, other.get_y()) + assert dx <= 1e-12 or dy <= 1e-12 + assert sum(p.get_width() * p.get_height() for p in patches) == pytest.approx( + width * height + ) + + +@pytest.mark.parametrize("rect", [(0, 0, 1, 1), (-2, 3, 4, 1), (1, -3, 1, 4)]) +def test_treemap_proportional_area_and_no_overlap(rect): + values = [3, 12, 1, 7, 2] + fig, ax = uplt.subplots() + try: + result = ax.treemap(values, labels=list("ABCDE"), rect=rect, pad=0) + areas = [p.get_width() * p.get_height() for p in result["patches"]] + np.testing.assert_allclose( + areas, np.array(values) / sum(values) * rect[2] * rect[3] + ) + _assert_tiling(result["patches"], rect) + assert result["values"] == values + assert [text.get_text() for text in result["texts"]] == list("ABCDE") + fig.canvas.draw() + finally: + uplt.close(fig) + + +def test_treemap_hierarchy_preserves_totals_and_contains_descendants(): + data = {"A": {"a": 4, "nested": {"b": 2, "c": 1}}, "B": {"d": 2}, "E": 1} + fig, ax = uplt.subplots() + try: + result = ax.treemap(data, pad=0, group_pad=0, group_labels=False) + assert result["paths"] == [ + ("A", "a"), + ("A", "nested", "b"), + ("A", "nested", "c"), + ("B", "d"), + ("E",), + ] + np.testing.assert_allclose( + [p.get_width() * p.get_height() for p in result["patches"]], + np.array([4, 2, 1, 2, 1]) / 10, + ) + _assert_tiling(result["patches"], (0, 0, 1, 1)) + assert len(result["groups"]) == 3 + for group, prefix in zip(result["groups"], [("A",), ("A", "nested"), ("B",)]): + for patch, path in zip(result["patches"], result["paths"]): + if path[: len(prefix)] == prefix: + assert patch.get_x() >= group.get_x() - 1e-12 + assert patch.get_y() >= group.get_y() - 1e-12 + assert ( + patch.get_x() + patch.get_width() + <= group.get_x() + group.get_width() + 1e-12 + ) + assert ( + patch.get_y() + patch.get_height() + <= group.get_y() + group.get_height() + 1e-12 + ) + finally: + uplt.close(fig) + + +def test_treemap_colormap_colorbar_and_zero_alignment(): + fig, ax = uplt.subplots() + try: + norm = Normalize(0, 8) + result = ax.treemap( + {"small": 1, "zero": 0, "large": 7}, cmap="viridis", norm=norm + ) + assert result["paths"] == [("small",), ("large",)] + for patch, value in zip(result["patches"], [1, 7]): + np.testing.assert_allclose( + patch.get_facecolor(), result["mappable"].to_rgba(value) + ) + ax.colorbar(result["mappable"], label="Size") + fig.canvas.draw() + finally: + uplt.close(fig) + + +def test_treemap_series_and_lookup_data(): + fig, axs = uplt.subplots(ncols=2) + try: + series = pd.Series([1, 3], index=["A", "B"]) + result = axs[0].treemap(series, color=["red", "blue"]) + assert result["paths"] == [("A",), ("B",)] + for patch, color in zip(result["patches"], ["red", "blue"]): + np.testing.assert_allclose(patch.get_facecolor(), to_rgba(color)) + lookup = {"amount": [1, 3], "names": ["A", "B"]} + other = axs[1].treemap( + "amount", + labels="names", + data=lookup, + show_values=True, + value_format="{:.1f}", + ) + assert [text.get_text() for text in other["texts"]] == ["A\n1.0", "B\n3.0"] + finally: + uplt.close(fig) + + +@pytest.mark.parametrize( + "sizes,kwargs", + [ + ([], {}), + ([0, 0], {}), + ([1, -1], {}), + ([1, np.nan], {}), + ([1, np.inf], {}), + ([[1, 2]], {}), + ({"A": {}}, {}), + ([1, 2], {"labels": ["A"]}), + ([1], {"pad": -1}), + ([1], {"rect": (0, 0, 0, 1)}), + ([1], {"color": "red", "cmap": "viridis"}), + ([1, 2], {"color": ["red", "blue", "green"]}), + ], +) +def test_treemap_invalid_data_does_not_add_artists(sizes, kwargs): + fig, ax = uplt.subplots() + before = (list(ax.patches), list(ax.texts)) + try: + with pytest.raises(ValueError): + ax.treemap(sizes, **kwargs) + assert list(ax.patches) == before[0] + assert list(ax.texts) == before[1] + finally: + uplt.close(fig) + + +def test_treemap_padding_and_styles_do_not_mutate_input(): + data = {"Group": {"Alpha": 3, "Beta": 2}, "Other": 1} + text_kw = {"fontsize": 8} + group_kw = {"lw": 2} + fig, ax = uplt.subplots() + try: + result = ax.treemap( + data, pad=0.02, show_values=True, text_kw=text_kw, group_kw=group_kw, lw=1.5 + ) + assert text_kw == {"fontsize": 8} + assert group_kw == {"lw": 2} + assert data == {"Group": {"Alpha": 3, "Beta": 2}, "Other": 1} + assert all(p.get_linewidth() == 1.5 for p in result["patches"]) + assert result["groups"][0].get_linewidth() == 2 + assert all(text.get_clip_on() for text in result["texts"]) + fig.canvas.draw() + finally: + uplt.close(fig) + + +@pytest.mark.parametrize( + "projection,scale", [("polar", None), (None, "log"), (None, "symlog")] +) +def test_treemap_rejects_axes_that_distort_area(projection, scale): + fig, axs = uplt.subplots(proj=projection) + ax = axs[0] + try: + if scale is not None: + ax.set_xscale(scale) + before = list(ax.patches) + with pytest.raises(ValueError, match="Cartesian axes with linear scales"): + ax.treemap([1, 2]) + assert list(ax.patches) == before + finally: + uplt.close(fig) From a3ae7a6442f5ccc0f5b74995cd1f391dd90b2b5f Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Tue, 3 Nov 2026 14:19:23 +1000 Subject: [PATCH 02/11] Move treemap defaults to rc settings and add type annotations --- ultraplot/axes/plot.py | 74 +++++++---- ultraplot/axes/plot_types/treemap.py | 187 ++++++++++++++++++--------- ultraplot/internals/rcsetup.py | 102 +++++++++++++++ ultraplot/tests/test_treemap.py | 182 ++++++++++++++++++++++++++ 4 files changed, 462 insertions(+), 83 deletions(-) diff --git a/ultraplot/axes/plot.py b/ultraplot/axes/plot.py index 9087abd13..3a6d0b6e6 100644 --- a/ultraplot/axes/plot.py +++ b/ultraplot/axes/plot.py @@ -11,7 +11,17 @@ import sys from collections.abc import Callable, Iterable from numbers import Integral, Number -from typing import Any, Literal, Iterable, Mapping, Optional, Sequence, TypeAlias, Union +from typing import ( + TYPE_CHECKING, + Any, + Literal, + Iterable, + Mapping, + Optional, + Sequence, + TypeAlias, + Union, +) import matplotlib as mpl import matplotlib.artist as martist @@ -62,6 +72,16 @@ __all__ = ["PlotAxes"] +if TYPE_CHECKING: + from .plot_types.treemap import ( + Bounds, + TreemapColors, + TreemapData, + TreemapInput, + TreemapResult, + ValueFormat, + ) + # Constants # NOTE: Increased from native linewidth of 0.25 matplotlib uses for grid box edges. @@ -6751,25 +6771,25 @@ def violinploth(self, *args, **kwargs): def treemap( self, - sizes, - labels=None, + sizes: "TreemapInput", + labels: Sequence[Any] | str | None = None, *, - data=None, - color=None, - cmap=None, - norm=None, - vmin=None, - vmax=None, - rect=(0, 0, 1, 1), - pad=0.008, - group_pad=0.018, - group_labels=True, - show_values=False, - value_format="{:g}", - text_kw=None, - group_kw=None, - **kwargs, - ): + data: "TreemapData | None" = None, + color: "TreemapColors | None" = None, + cmap: str | mcolors.Colormap | None = None, + norm: mcolors.Normalize | None = None, + vmin: float | None = None, + vmax: float | None = None, + rect: "Bounds | None" = None, + pad: float | None = None, + group_pad: float | None = None, + group_labels: bool | None = None, + show_values: bool | None = None, + value_format: "ValueFormat | None" = None, + text_kw: Mapping[str, Any] | None = None, + group_kw: Mapping[str, Any] | None = None, + **kwargs: Any, + ) -> "TreemapResult": """Draw an area-proportional treemap of flat or hierarchical data. Requires Cartesian axes with linear scales. @@ -6796,26 +6816,30 @@ def treemap( Normalization for ``cmap``. Cannot be combined with vmin/vmax. vmin, vmax : float, optional Colormap bounds when ``norm`` is omitted. - rect : tuple of float, default: (0, 0, 1, 1) + rect : tuple of float, default: :rc:`treemap.rect` Bounding rectangle as (x, y, width, height), in data coordinates. The axes uses equal scaling so tile areas are not distorted. - pad, group_pad : float, default: 0.008, 0.018 + pad, group_pad : float, default: :rc:`treemap.pad`, :rc:`treemap.group_pad` Gaps between leaf tiles and group frames in data coordinates. Padding and group headings reduce the visible area of each tile; use zero padding and ``group_labels=False`` for exact area ratios. - group_labels : bool, default: True + group_labels : bool, default: :rc:`treemap.group_labels` Reserve a header for each group name. - show_values : bool, default: False + show_values : bool, default: :rc:`treemap.show_values` Add the numeric size below each leaf label. - value_format : str or callable, default: '{:g}' + value_format : str or callable, default: :rc:`treemap.value_format` Format string or function used by ``show_values``. text_kw, group_kw : dict, optional Leaf text properties and group rectangle properties. Text is clipped to its tile. Other keyword arguments style leaf rectangles. + Explicit properties override the ``treemap.patch.*``, + ``treemap.group.*``, and ``treemap.text.*`` rc defaults. Group label + size and weight follow ``treemap.group.text.*``. Omitted options + are resolved from rc at call time; explicit False and zero win. Returns ------- - dict + TreemapResult ``patches``, ``texts``, ``paths``, and ``values`` follow input leaf order, omitting zeros. ``texts`` includes None for unlabeled tiles. ``groups`` and ``group_texts`` contain group artists. ``mappable`` diff --git a/ultraplot/axes/plot_types/treemap.py b/ultraplot/axes/plot_types/treemap.py index 20832c9ad..3adb5102e 100644 --- a/ultraplot/axes/plot_types/treemap.py +++ b/ultraplot/axes/plot_types/treemap.py @@ -1,28 +1,65 @@ """Area-proportional, squarified treemaps using native Matplotlib artists.""" -from collections.abc import Mapping +from __future__ import annotations + +from collections.abc import Callable, Hashable, Mapping, Sequence from dataclasses import dataclass import math +from typing import TYPE_CHECKING, Any, TypeAlias, TypedDict, Union, cast import matplotlib.cm as mcm import matplotlib.colors as mcolors from matplotlib.patches import Rectangle +from matplotlib.text import Text import numpy as np +from numpy.typing import ArrayLike, NDArray from ... import constructor from ...config import rc -from ...internals import _pop_props +from ...internals import _not_none, _pop_props + +if TYPE_CHECKING: + from pandas import DataFrame, Series + + from ..plot import PlotAxes + +Bounds: TypeAlias = tuple[float, float, float, float] +TreemapHierarchy: TypeAlias = Mapping[Hashable, Union[float, "TreemapHierarchy"]] +TreemapInput: TypeAlias = Union[ArrayLike, TreemapHierarchy, "Series"] +TreemapData: TypeAlias = Union[Mapping[str, Any], "DataFrame"] +TreemapColor: TypeAlias = ( + str | tuple[float, float, float] | tuple[float, float, float, float] +) +TreemapColors: TypeAlias = TreemapColor | Sequence[TreemapColor] | NDArray[Any] +ValueFormat: TypeAlias = str | Callable[[float], str] +NodePath: TypeAlias = tuple[Hashable, ...] + + +class TreemapResult(TypedDict): + """Treemap artists and metadata, with leaves in their original input order.""" + + patches: list[Rectangle] + texts: list[Text | None] + groups: list[Rectangle] + group_texts: list[Text] + paths: list[NodePath] + values: list[float] + mappable: mcm.ScalarMappable | None @dataclass class _Node: label: str value: float - path: tuple - children: tuple = () + path: NodePath + children: tuple[_Node, ...] = () -def _nodes(sizes, labels=None, path=()): +def _nodes( + sizes: TreemapInput, + labels: Sequence[Any] | None = None, + path: NodePath = (), +) -> list[_Node]: """Validate the complete hierarchy before adding any artists.""" if isinstance(sizes, Mapping) or ( getattr(sizes, "ndim", None) == 1 and hasattr(sizes, "items") @@ -30,10 +67,11 @@ def _nodes(sizes, labels=None, path=()): if labels is not None: raise ValueError("Mapping and Series inputs already supply their labels.") result = [] - for key, value in sizes.items(): + # Series is duck-typed so pandas remains an optional dependency. + for key, value in cast(Mapping[Hashable, Any], sizes).items(): child_path = (*path, key) if isinstance(value, Mapping): - children = _nodes(value, path=child_path) + children = _nodes(cast(TreemapHierarchy, value), path=child_path) total = math.fsum(child.value for child in children) result.append(_Node(str(key), total, child_path, tuple(children))) else: @@ -60,7 +98,7 @@ def _nodes(sizes, labels=None, path=()): return result -def _value(value): +def _value(value: Any) -> float: try: value = float(value) except (TypeError, ValueError) as exc: @@ -70,7 +108,7 @@ def _value(value): return value -def _squarify(nodes, rect): +def _squarify(nodes: Sequence[_Node], rect: Bounds) -> list[tuple[_Node, Bounds]]: """Tile a rectangle with compact strips, retaining each node's identity.""" x, y, width, height = rect ordered = sorted((node for node in nodes if node.value > 0), key=lambda n: -n.value) @@ -78,9 +116,9 @@ def _squarify(nodes, rect): weights = [node.value / scale for node in ordered] total = math.fsum(weights) areas = [weight / total * width * height for weight in weights] - result = [] + result: list[tuple[_Node, Bounds]] = [] - def worst(row, side): + def worst(row: list[tuple[_Node, float]], side: float) -> float: total = math.fsum(area for _, area in row) smallest = min(area for _, area in row) largest = max(area for _, area in row) @@ -88,7 +126,13 @@ def worst(row, side): side * side * largest / total**2, total**2 / (side * side * smallest) ) - def place(row, x, y, width, height): + def place( + row: list[tuple[_Node, float]], + x: float, + y: float, + width: float, + height: float, + ) -> Bounds: area = math.fsum(size for _, size in row) if width >= height: strip = area / height @@ -106,7 +150,7 @@ def place(row, x, y, width, height): offset += length return x, y + strip, width, max(0, height - strip) - row = [] + row: list[tuple[_Node, float]] = [] for node, area in zip(ordered, areas): candidate = [*row, (node, area)] if row and worst(candidate, min(width, height)) > worst( @@ -120,38 +164,57 @@ def place(row, x, y, width, height): return result -def _inset(rect, pad): +def _inset(rect: Bounds, pad: float) -> Bounds: x, y, width, height = rect inset = min(pad / 2, width * 0.2, height * 0.2) return x + inset, y + inset, width - 2 * inset, height - 2 * inset def treemap( - ax, - sizes, - labels=None, + ax: PlotAxes, + sizes: TreemapInput, + labels: Sequence[Any] | None = None, *, - color=None, - cmap=None, - norm=None, - vmin=None, - vmax=None, - rect=(0, 0, 1, 1), - pad=0.008, - group_pad=0.018, - group_labels=True, - show_values=False, - value_format="{:g}", - text_kw=None, - group_kw=None, - **kwargs, -): + color: TreemapColors | None = None, + cmap: str | mcolors.Colormap | None = None, + norm: mcolors.Normalize | None = None, + vmin: float | None = None, + vmax: float | None = None, + rect: Bounds | None = None, + pad: float | None = None, + group_pad: float | None = None, + group_labels: bool | None = None, + show_values: bool | None = None, + value_format: ValueFormat | None = None, + text_kw: Mapping[str, Any] | None = None, + group_kw: Mapping[str, Any] | None = None, + **kwargs: Any, +) -> TreemapResult: + """Resolve rc defaults and draw :meth:`PlotAxes.treemap`.""" + rect = cast(Bounds, _not_none(rect, rc["treemap.rect"])) + pad = cast(float, _not_none(pad, rc["treemap.pad"])) + group_pad = cast(float, _not_none(group_pad, rc["treemap.group_pad"])) + group_labels = cast(bool, _not_none(group_labels, rc["treemap.group_labels"])) + show_values = cast(bool, _not_none(show_values, rc["treemap.show_values"])) + value_format = cast( + ValueFormat, _not_none(value_format, rc["treemap.value_format"]) + ) if not ax.transData.is_affine: raise ValueError("treemap requires Cartesian axes with linear scales.") nodes = _nodes(sizes, labels) - rect = np.asarray(rect, dtype=float) - if rect.shape != (4,) or not np.all(np.isfinite(rect)) or np.any(rect[2:] <= 0): + rect_array = np.asarray(rect, dtype=float) + if ( + rect_array.shape != (4,) + or not np.all(np.isfinite(rect_array)) + or np.any(rect_array[2:] <= 0) + ): raise ValueError("rect must be (x, y, width, height) with positive dimensions.") + rect = ( + float(rect_array[0]), + float(rect_array[1]), + float(rect_array[2]), + float(rect_array[3]), + ) if not np.isfinite(pad) or pad < 0 or not np.isfinite(group_pad) or group_pad < 0: raise ValueError("pad and group_pad must be finite and nonnegative.") if color is not None and cmap is not None: @@ -159,9 +222,9 @@ def treemap( if not callable(value_format) and not isinstance(value_format, str): raise ValueError("value_format must be a format string or callable.") - leaves = [] + leaves: list[_Node] = [] - def collect(branch): + def collect(branch: Sequence[_Node]) -> None: for node in branch: if node.children: collect(node.children) @@ -170,8 +233,8 @@ def collect(branch): collect(nodes) values = np.array([node.value for node in leaves]) - mappable = None - colors = {} + mappable: mcm.ScalarMappable | None = None + colors: dict[int, NDArray[np.float64]] = {} if cmap is not None: if norm is None: norm = mcolors.Normalize(vmin=vmin, vmax=vmax) @@ -194,22 +257,25 @@ def collect(branch): raise ValueError("norm, vmin, and vmax require cmap.") cycle = constructor.Cycle(rc["cycle"]).by_key()["color"] - style = dict(kwargs) + style: dict[str, Any] = dict(kwargs) style.update(_pop_props(style, "patch")) - style.setdefault("edgecolor", "white") - style.setdefault("linewidth", 0.6) - parent_style = dict(group_kw or {}) + style.setdefault("edgecolor", rc["treemap.patch.edgecolor"]) + style.setdefault("linewidth", rc["treemap.patch.linewidth"]) + parent_style: dict[str, Any] = dict(group_kw or {}) parent_style.update(_pop_props(parent_style, "patch")) - parent_style.setdefault("edgecolor", "white") - parent_style.setdefault("linewidth", 1.2) - text_style = dict(text_kw or {}) - text_style.setdefault("fontsize", 9) + parent_style.setdefault("edgecolor", rc["treemap.group.edgecolor"]) + parent_style.setdefault("linewidth", rc["treemap.group.linewidth"]) + parent_style.setdefault("alpha", rc["treemap.group.alpha"]) + text_style: dict[str, Any] = dict(text_kw or {}) + text_style.update(_pop_props(text_style, "text")) + text_style.setdefault("fontsize", rc["treemap.text.size"]) + text_style.setdefault("color", rc["treemap.text.color"]) text_style.setdefault("ha", "center") text_style.setdefault("va", "center") text_style.setdefault("clip_on", True) # Format all values before drawing so a bad formatter leaves the axes untouched. - formatted = {} + formatted: dict[int, str] = {} if show_values: for node in leaves: formatted[id(node)] = str( @@ -218,7 +284,7 @@ def collect(branch): else value_format.format(node.value) ) - result = { + result: TreemapResult = { "patches": [], "texts": [], "groups": [], @@ -227,15 +293,17 @@ def collect(branch): "values": [], "mappable": mappable, } - drawn = {} + drawn: dict[int, tuple[Rectangle, Text | None]] = {} - def draw(branch, bounds, base_color=None): + def draw( + branch: Sequence[_Node], bounds: Bounds, base_color: TreemapColor | None = None + ) -> None: for index, (node, box) in enumerate(_squarify(branch, bounds)): hue = base_color if base_color is not None else cycle[index % len(cycle)] if node.children: box = _inset(box, group_pad) x, y, width, height = box - group_style = {"facecolor": hue, "alpha": 0.12, **parent_style} + group_style: dict[str, Any] = {"facecolor": hue, **parent_style} patch = Rectangle((x, y), width, height, **group_style) ax.add_patch(patch) result["groups"].append(patch) @@ -246,8 +314,8 @@ def draw(branch, bounds, base_color=None): inner[0], inner[1] + inner[3] - header / 2, node.label, - fontsize=10, - fontweight="bold", + fontsize=rc["treemap.group.text.size"], + fontweight=rc["treemap.group.text.weight"], ha="left", va="center", clip_on=True, @@ -263,7 +331,8 @@ def draw(branch, bounds, base_color=None): rgb = np.array(mcolors.to_rgb(hue)) blend = 0.10 + 0.12 * (index % 4) if base_color is not None else 0 rgba = rgb * (1 - blend) + blend - patch = Rectangle((x, y), width, height, **{"facecolor": rgba, **style}) + leaf_style: dict[str, Any] = {"facecolor": rgba, **style} + patch = Rectangle((x, y), width, height, **leaf_style) ax.add_patch(patch) text = node.label if show_values: @@ -273,10 +342,12 @@ def draw(branch, bounds, base_color=None): luminance = np.dot( patch.get_facecolor()[:3], [0.2126, 0.7152, 0.0722] ) - options = { - "color": "#18212b" if luminance > 0.5 else "white", - **text_style, - } + options = dict(text_style) + if ( + isinstance(options["color"], str) + and options["color"].lower() == "auto" + ): + options["color"] = "#18212b" if luminance > 0.5 else "white" artist = ax.text(x + width / 2, y + height / 2, text, **options) artist.set_clip_path(patch) drawn[id(node)] = patch, artist diff --git a/ultraplot/internals/rcsetup.py b/ultraplot/internals/rcsetup.py index 27737fbce..24ffefff1 100644 --- a/ultraplot/internals/rcsetup.py +++ b/ultraplot/internals/rcsetup.py @@ -8,6 +8,7 @@ import sys from collections.abc import MutableMapping from numbers import Integral, Real +from typing import Any, Callable import matplotlib as mpl import matplotlib.rcsetup as msetup @@ -525,6 +526,39 @@ def _validate_tuple_float_2(value): raise ValueError(f"Value must be a tuple/list of 2 floats, got {value!r}") +def _validate_treemap_rect(value: Any) -> tuple[float, float, float, float]: + """Validate treemap bounds from Python values or a comma-separated rc entry.""" + if isinstance(value, str): + value = value.strip("()[]").split(",") + array = np.asarray(value, dtype=float) + if array.shape != (4,) or not np.all(np.isfinite(array)) or np.any(array[2:] <= 0): + raise ValueError( + "treemap.rect must be (x, y, width, height) with positive dimensions." + ) + return float(array[0]), float(array[1]), float(array[2]), float(array[3]) + + +def _validate_treemap_format(value: Any) -> str | Callable[[float], str]: + """Permit format strings in rc files and formatting callables in contexts.""" + if isinstance(value, str) or callable(value): + return value + raise ValueError("treemap.value_format must be a format string or callable.") + + +def _validate_nonnegative_float(value: Any) -> float: + value = _validate_float(value) + if not np.isfinite(value) or value < 0: + raise ValueError("Value must be finite and nonnegative.") + return value + + +def _validate_treemap_alpha(value: Any) -> float: + value = _validate_nonnegative_float(value) + if value > 1: + raise ValueError("Opacity must be between zero and one.") + return value + + def _rst_table(): """ Return the setting names and descriptions in an RST-style table. @@ -1992,6 +2026,74 @@ def _validator_accepts(validator, value): _validate_float, "Z-order for internal political border lines.", ), + # Treemap settings + "treemap.rect": ( + (0.0, 0.0, 1.0, 1.0), + _validate_treemap_rect, + "Treemap bounds as (x, y, width, height).", + ), + "treemap.pad": ( + 0.008, + _validate_nonnegative_float, + "Gap between treemap leaves, in data coordinates.", + ), + "treemap.group_pad": ( + 0.018, + _validate_nonnegative_float, + "Padding around treemap groups, in data coordinates.", + ), + "treemap.group_labels": ( + True, + _validate_bool, + "Whether treemap groups have labeled headers.", + ), + "treemap.show_values": ( + False, + _validate_bool, + "Whether treemap leaves display their numeric size.", + ), + "treemap.value_format": ( + "{:g}", + _validate_treemap_format, + "Format string or callable for treemap values.", + ), + "treemap.patch.edgecolor": ("white", _validate_color, "Treemap leaf edge color."), + "treemap.patch.linewidth": ( + 0.6, + _validate_pt, + "Treemap leaf edge width." + _addendum_pt, + ), + "treemap.group.edgecolor": ("white", _validate_color, "Treemap group edge color."), + "treemap.group.linewidth": ( + 1.2, + _validate_pt, + "Treemap group edge width." + _addendum_pt, + ), + "treemap.group.alpha": ( + 0.12, + _validate_treemap_alpha, + "Treemap group background opacity.", + ), + "treemap.text.size": ( + 9.0, + _validate_fontsize, + "Treemap leaf label font size." + _addendum_pt, + ), + "treemap.text.color": ( + "auto", + functools.partial(_validate_color, alternative="auto"), + "Treemap leaf label color; auto selects dark or white text for contrast.", + ), + "treemap.group.text.size": ( + 10.0, + _validate_fontsize, + "Treemap group label font size." + _addendum_pt, + ), + "treemap.group.text.weight": ( + "bold", + _validate_fontweight, + "Treemap group label font weight.", + ), # Raincloud plot settings "raincloud.orientation": ( "vertical", diff --git a/ultraplot/tests/test_treemap.py b/ultraplot/tests/test_treemap.py index d2b549d9c..47c5b988b 100644 --- a/ultraplot/tests/test_treemap.py +++ b/ultraplot/tests/test_treemap.py @@ -1,5 +1,7 @@ """Treemap area conservation, hierarchy, and public plotting behavior.""" +from pathlib import Path + import numpy as np import pandas as pd import pytest @@ -185,3 +187,183 @@ def test_treemap_rejects_axes_that_distort_area(projection, scale): assert list(ax.patches) == before finally: uplt.close(fig) + + +def test_treemap_rc_layout_and_appearance() -> None: + settings = { + "treemap.rect": (2, 3, 2, 1), + "treemap.pad": 0.025, + "treemap.group_pad": 0.03, + "treemap.group_labels": True, + "treemap.show_values": True, + "treemap.value_format": "{:.1f} kg", + "treemap.patch.edgecolor": "navy", + "treemap.patch.linewidth": 2, + "treemap.group.edgecolor": "red", + "treemap.group.linewidth": 3, + "treemap.group.alpha": 0.4, + "treemap.text.size": 12, + "treemap.text.color": "purple", + "treemap.group.text.size": 14, + "treemap.group.text.weight": "normal", + } + before = {key: uplt.rc[key] for key in settings} + fig, axs = uplt.subplots() + ax = axs[0] + try: + with uplt.rc.context(settings): + result = ax.treemap({"Group": {"A": 3, "B": 1}}) + assert {key: uplt.rc[key] for key in settings} == before + np.testing.assert_allclose(ax.get_xlim(), [2, 4]) + np.testing.assert_allclose(ax.get_ylim(), [3, 4]) + assert [text.get_text() for text in result["texts"]] == [ + "A\n3.0 kg", + "B\n1.0 kg", + ] + for patch, text in zip(result["patches"], result["texts"]): + assert patch.get_linewidth() == 2 + np.testing.assert_allclose(patch.get_edgecolor(), to_rgba("navy")) + assert text.get_fontsize() == 12 + assert text.get_color() == "purple" + group = result["groups"][0] + assert group.get_alpha() == 0.4 + assert group.get_linewidth() == 3 + np.testing.assert_allclose(group.get_edgecolor(), to_rgba("red", 0.4)) + header = result["group_texts"][0] + assert header.get_fontsize() == 14 + assert header.get_fontweight() == "normal" + fig.canvas.draw() + finally: + uplt.close(fig) + + +def test_treemap_explicit_options_and_aliases_override_rc() -> None: + settings = { + "treemap.rect": (5, 5, 2, 2), + "treemap.pad": 0.1, + "treemap.group_pad": 0.1, + "treemap.group_labels": True, + "treemap.show_values": True, + "treemap.patch.linewidth": 2, + "treemap.group.alpha": 0.5, + "treemap.text.color": "red", + "treemap.text.size": 20, + } + fig, ax = uplt.subplots() + try: + with uplt.rc.context(settings): + result = ax.treemap( + {"Group": {"A": 3, "B": 1}}, + rect=(0, 0, 1, 1), + pad=0, + group_pad=0, + group_labels=False, + show_values=False, + lw=0, + text_kw={"c": "navy", "size": 8}, + group_kw={"a": 0, "lw": 0}, + ) + _assert_tiling(result["patches"], (0, 0, 1, 1)) + assert not result["group_texts"] + assert [text.get_text() for text in result["texts"]] == ["A", "B"] + assert all(p.get_linewidth() == 0 for p in result["patches"]) + assert all(text.get_color() == "navy" for text in result["texts"]) + assert all(text.get_fontsize() == 8 for text in result["texts"]) + assert result["groups"][0].get_alpha() == 0 + assert result["groups"][0].get_linewidth() == 0 + finally: + uplt.close(fig) + + +def test_treemap_rc_file_and_context_restore(tmp_path: Path) -> None: + path = tmp_path / "treemap.rc" + path.write_text( + "treemap.rect: 1, 2, 3, 4\n" + "treemap.pad: 0\n" + "treemap.group_labels: False\n" + "treemap.show_values: True\n" + "treemap.value_format: {:.1f}\n" + "treemap.text.color: navy\n" + ) + before = uplt.rc["treemap.rect"] + fig, axs = uplt.subplots() + ax = axs[0] + try: + with uplt.rc.context(file=str(path)): + result = ax.treemap({"A": 3, "B": 1}) + assert uplt.rc["treemap.rect"] == (1, 2, 3, 4) + assert uplt.rc["treemap.rect"] == before + _assert_tiling(result["patches"], (1, 2, 3, 4)) + assert result["texts"][0].get_text() == "A\n3.0" + assert result["texts"][0].get_color() == "navy" + finally: + uplt.close(fig) + + +def test_treemap_callable_rc_formatter_and_call_override() -> None: + fig, axs = uplt.subplots(ncols=2) + try: + with uplt.rc.context( + { + "treemap.value_format": lambda value: f"{value:.0f}kg", + "treemap.show_values": True, + } + ): + first = axs[0].treemap([3], labels=["A"]) + second = axs[1].treemap([3], labels=["A"], value_format="{:.1f}") + assert first["texts"][0].get_text() == "A\n3kg" + assert second["texts"][0].get_text() == "A\n3.0" + finally: + uplt.close(fig) + + +@pytest.mark.parametrize( + "key,value", + [ + ("treemap.rect", (0, 0, 0, 1)), + ("treemap.rect", (0, 1)), + ("treemap.pad", -0.1), + ("treemap.group_pad", float("nan")), + ("treemap.group.alpha", 1.5), + ("treemap.value_format", 42), + ], +) +def test_treemap_rc_rejects_invalid_settings(key: str, value: object) -> None: + before = uplt.rc[key] + with pytest.raises(ValueError): + uplt.rc[key] = value + assert uplt.rc[key] == before + + +def test_treemap_defaults_match_original_appearance() -> None: + fig, axs = uplt.subplots(ncols=2) + data = {"Group": {"A": 3, "B": 1}, "Other": 2} + try: + default = axs[0].treemap(data) + explicit = axs[1].treemap( + data, + rect=(0, 0, 1, 1), + pad=0.008, + group_pad=0.018, + group_labels=True, + show_values=False, + value_format="{:g}", + ec="white", + lw=0.6, + text_kw={"fontsize": 9}, + group_kw={"ec": "white", "lw": 1.2, "alpha": 0.12}, + ) + for key in ("patches", "groups"): + for actual, expected in zip(default[key], explicit[key]): + np.testing.assert_allclose( + actual.get_bbox().bounds, expected.get_bbox().bounds + ) + np.testing.assert_allclose( + actual.get_facecolor(), expected.get_facecolor() + ) + assert actual.get_linewidth() == expected.get_linewidth() + for actual, expected in zip(default["texts"], explicit["texts"]): + assert actual.get_fontsize() == expected.get_fontsize() + assert actual.get_color() == expected.get_color() + finally: + uplt.close(fig) From 3f906a22e6bb4ff41fe34aef7390b3ae1795635d Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Tue, 3 Nov 2026 14:31:36 +1000 Subject: [PATCH 03/11] Simplify treemap validation, layout, and rendering --- ultraplot/axes/plot_types/treemap.py | 236 +++++++---------- ultraplot/tests/test_treemap.py | 362 ++++++++++++--------------- 2 files changed, 256 insertions(+), 342 deletions(-) diff --git a/ultraplot/axes/plot_types/treemap.py b/ultraplot/axes/plot_types/treemap.py index 3adb5102e..9ee7f1e34 100644 --- a/ultraplot/axes/plot_types/treemap.py +++ b/ultraplot/axes/plot_types/treemap.py @@ -2,7 +2,7 @@ from __future__ import annotations -from collections.abc import Callable, Hashable, Mapping, Sequence +from collections.abc import Callable, Hashable, Iterator, Mapping, Sequence from dataclasses import dataclass import math from typing import TYPE_CHECKING, Any, TypeAlias, TypedDict, Union, cast @@ -17,6 +17,11 @@ from ... import constructor from ...config import rc from ...internals import _not_none, _pop_props +from ...internals.rcsetup import ( + _validate_nonnegative_float, + _validate_treemap_format, + _validate_treemap_rect, +) if TYPE_CHECKING: from pandas import DataFrame, Series @@ -54,6 +59,13 @@ class _Node: path: NodePath children: tuple[_Node, ...] = () + def leaves(self) -> Iterator[_Node]: + if self.children: + for child in self.children: + yield from child.leaves() + elif self.value > 0: + yield self + def _nodes( sizes: TreemapInput, @@ -75,7 +87,9 @@ def _nodes( total = math.fsum(child.value for child in children) result.append(_Node(str(key), total, child_path, tuple(children))) else: - result.append(_Node(str(key), _value(value), child_path)) + result.append( + _Node(str(key), _validate_nonnegative_float(value), child_path) + ) else: try: values = np.ma.asarray(sizes, dtype=float).filled(np.nan) @@ -90,7 +104,7 @@ def _nodes( elif isinstance(labels, str) or len(labels) != len(values): raise ValueError("labels must have the same length as sizes.") result = [ - _Node(str(label), _value(value), (index,)) + _Node(str(label), _validate_nonnegative_float(value), (index,)) for index, (value, label) in enumerate(zip(values, labels)) ] if not result or not any(node.value > 0 for node in result): @@ -98,16 +112,6 @@ def _nodes( return result -def _value(value: Any) -> float: - try: - value = float(value) - except (TypeError, ValueError) as exc: - raise ValueError("sizes must contain finite, nonnegative numbers.") from exc - if not math.isfinite(value) or value < 0: - raise ValueError("sizes must contain finite, nonnegative numbers.") - return value - - def _squarify(nodes: Sequence[_Node], rect: Bounds) -> list[tuple[_Node, Bounds]]: """Tile a rectangle with compact strips, retaining each node's identity.""" x, y, width, height = rect @@ -126,29 +130,22 @@ def worst(row: list[tuple[_Node, float]], side: float) -> float: side * side * largest / total**2, total**2 / (side * side * smallest) ) - def place( - row: list[tuple[_Node, float]], - x: float, - y: float, - width: float, - height: float, - ) -> Bounds: + def place(row: list[tuple[_Node, float]], bounds: Bounds) -> Bounds: + x, y, width, height = bounds area = math.fsum(size for _, size in row) - if width >= height: - strip = area / height - offset = y - for node, size in row: - length = size / strip - result.append((node, (x, offset, strip, length))) - offset += length - return x + strip, y, max(0, width - strip), height - strip = area / width - offset = x + vertical = width >= height + strip = area / min(width, height) + offset = y if vertical else x for node, size in row: length = size / strip - result.append((node, (offset, y, length, strip))) + box = (x, offset, strip, length) if vertical else (offset, y, length, strip) + result.append((node, box)) offset += length - return x, y + strip, width, max(0, height - strip) + return ( + (x + strip, y, max(0, width - strip), height) + if vertical + else (x, y + strip, width, max(0, height - strip)) + ) row: list[tuple[_Node, float]] = [] for node, area in zip(ordered, areas): @@ -156,11 +153,11 @@ def place( if row and worst(candidate, min(width, height)) > worst( row, min(width, height) ): - x, y, width, height = place(row, x, y, width, height) + x, y, width, height = place(row, (x, y, width, height)) row = [] row.append((node, area)) if row: - place(row, x, y, width, height) + place(row, (x, y, width, height)) return result @@ -170,6 +167,16 @@ def _inset(rect: Bounds, pad: float) -> Bounds: return x + inset, y + inset, width - 2 * inset, height - 2 * inset +def _style( + category: str, kind: str, options: Mapping[str, Any] | None = None +) -> dict[str, Any]: + """Canonicalize aliases before explicit properties override rc defaults.""" + defaults = rc.category("treemap." + category) + props = dict(options or {}) + props.update(_pop_props(props, kind)) + return {**_pop_props(defaults, kind), **props} + + def treemap( ax: PlotAxes, sizes: TreemapInput, @@ -191,50 +198,25 @@ def treemap( **kwargs: Any, ) -> TreemapResult: """Resolve rc defaults and draw :meth:`PlotAxes.treemap`.""" - rect = cast(Bounds, _not_none(rect, rc["treemap.rect"])) - pad = cast(float, _not_none(pad, rc["treemap.pad"])) - group_pad = cast(float, _not_none(group_pad, rc["treemap.group_pad"])) + rect = _validate_treemap_rect(_not_none(rect, rc["treemap.rect"])) + pad = _validate_nonnegative_float(_not_none(pad, rc["treemap.pad"])) + group_pad = _validate_nonnegative_float( + _not_none(group_pad, rc["treemap.group_pad"]) + ) group_labels = cast(bool, _not_none(group_labels, rc["treemap.group_labels"])) show_values = cast(bool, _not_none(show_values, rc["treemap.show_values"])) - value_format = cast( - ValueFormat, _not_none(value_format, rc["treemap.value_format"]) + value_format = _validate_treemap_format( + _not_none(value_format, rc["treemap.value_format"]) ) if not ax.transData.is_affine: raise ValueError("treemap requires Cartesian axes with linear scales.") nodes = _nodes(sizes, labels) - rect_array = np.asarray(rect, dtype=float) - if ( - rect_array.shape != (4,) - or not np.all(np.isfinite(rect_array)) - or np.any(rect_array[2:] <= 0) - ): - raise ValueError("rect must be (x, y, width, height) with positive dimensions.") - rect = ( - float(rect_array[0]), - float(rect_array[1]), - float(rect_array[2]), - float(rect_array[3]), - ) - if not np.isfinite(pad) or pad < 0 or not np.isfinite(group_pad) or group_pad < 0: - raise ValueError("pad and group_pad must be finite and nonnegative.") if color is not None and cmap is not None: raise ValueError("Use either color or cmap, not both.") - if not callable(value_format) and not isinstance(value_format, str): - raise ValueError("value_format must be a format string or callable.") - - leaves: list[_Node] = [] - - def collect(branch: Sequence[_Node]) -> None: - for node in branch: - if node.children: - collect(node.children) - elif node.value > 0: - leaves.append(node) - - collect(nodes) + leaves = [leaf for node in nodes for leaf in node.leaves()] values = np.array([node.value for node in leaves]) mappable: mcm.ScalarMappable | None = None - colors: dict[int, NDArray[np.float64]] = {} + colors: NDArray[np.float64] | None = None if cmap is not None: if norm is None: norm = mcolors.Normalize(vmin=vmin, vmax=vmax) @@ -243,59 +225,49 @@ def collect(branch: Sequence[_Node]) -> None: mappable = mcm.ScalarMappable(norm=norm, cmap=constructor.Colormap(cmap)) mappable.set_array(values) mappable.autoscale_None() - colors = { - id(node): rgba for node, rgba in zip(leaves, mappable.to_rgba(values)) - } + colors = mappable.to_rgba(values) elif color is not None: - rgba = mcolors.to_rgba_array(color) - if len(rgba) not in (1, len(leaves)): + colors = mcolors.to_rgba_array(color) + if len(colors) not in (1, len(leaves)): raise ValueError( "color must be a single color or one color per nonzero leaf." ) - colors = {id(node): rgba[i % len(rgba)] for i, node in enumerate(leaves)} elif norm is not None or vmin is not None or vmax is not None: raise ValueError("norm, vmin, and vmax require cmap.") cycle = constructor.Cycle(rc["cycle"]).by_key()["color"] - style: dict[str, Any] = dict(kwargs) - style.update(_pop_props(style, "patch")) - style.setdefault("edgecolor", rc["treemap.patch.edgecolor"]) - style.setdefault("linewidth", rc["treemap.patch.linewidth"]) - parent_style: dict[str, Any] = dict(group_kw or {}) - parent_style.update(_pop_props(parent_style, "patch")) - parent_style.setdefault("edgecolor", rc["treemap.group.edgecolor"]) - parent_style.setdefault("linewidth", rc["treemap.group.linewidth"]) - parent_style.setdefault("alpha", rc["treemap.group.alpha"]) - text_style: dict[str, Any] = dict(text_kw or {}) - text_style.update(_pop_props(text_style, "text")) - text_style.setdefault("fontsize", rc["treemap.text.size"]) - text_style.setdefault("color", rc["treemap.text.color"]) - text_style.setdefault("ha", "center") - text_style.setdefault("va", "center") - text_style.setdefault("clip_on", True) + style = _style("patch", "patch", kwargs) + parent_style = _style("group", "patch", group_kw) + text_style: dict[str, Any] = { + "ha": "center", + "va": "center", + "clip_on": True, + **_style("text", "text", text_kw), + } + group_text_style = _style("group.text", "text") + group_text_style.update(ha="left", va="center", clip_on=True) # Format all values before drawing so a bad formatter leaves the axes untouched. - formatted: dict[int, str] = {} + labels = [node.label for node in leaves] if show_values: - for node in leaves: - formatted[id(node)] = str( - value_format(node.value) - if callable(value_format) - else value_format.format(node.value) - ) + formatter = value_format if callable(value_format) else value_format.format + labels = [ + "\n".join(filter(None, (node.label, str(formatter(node.value))))) + for node in leaves + ] result: TreemapResult = { "patches": [], "texts": [], "groups": [], "group_texts": [], - "paths": [], - "values": [], + "paths": [node.path for node in leaves], + "values": values.tolist(), "mappable": mappable, } - drawn: dict[int, tuple[Rectangle, Text | None]] = {} + tiles: dict[int, tuple[Bounds, NDArray[np.float64]]] = {} - def draw( + def layout( branch: Sequence[_Node], bounds: Bounds, base_color: TreemapColor | None = None ) -> None: for index, (node, box) in enumerate(_squarify(branch, bounds)): @@ -314,52 +286,34 @@ def draw( inner[0], inner[1] + inner[3] - header / 2, node.label, - fontsize=rc["treemap.group.text.size"], - fontweight=rc["treemap.group.text.weight"], - ha="left", - va="center", - clip_on=True, + **group_text_style, ) label.set_clip_path(patch) result["group_texts"].append(label) - draw(node.children, (*inner[:3], inner[3] - header), hue) + layout(node.children, (*inner[:3], inner[3] - header), hue) else: - x, y, width, height = _inset(box, pad) - rgba = colors.get(id(node)) - if rgba is None: - # Related leaves share a hue, with gentle categorical shades. - rgb = np.array(mcolors.to_rgb(hue)) - blend = 0.10 + 0.12 * (index % 4) if base_color is not None else 0 - rgba = rgb * (1 - blend) + blend - leaf_style: dict[str, Any] = {"facecolor": rgba, **style} - patch = Rectangle((x, y), width, height, **leaf_style) - ax.add_patch(patch) - text = node.label - if show_values: - text = "\n".join(filter(None, [text, formatted[id(node)]])) - artist = None - if text: - luminance = np.dot( - patch.get_facecolor()[:3], [0.2126, 0.7152, 0.0722] - ) - options = dict(text_style) - if ( - isinstance(options["color"], str) - and options["color"].lower() == "auto" - ): - options["color"] = "#18212b" if luminance > 0.5 else "white" - artist = ax.text(x + width / 2, y + height / 2, text, **options) - artist.set_clip_path(patch) - drawn[id(node)] = patch, artist - - draw(nodes, rect) - # Public results retain input order even though the layout sorts by size. - for node in leaves: - patch, text = drawn[id(node)] + rgb = np.array(mcolors.to_rgb(hue)) + blend = 0.10 + 0.12 * (index % 4) if base_color is not None else 0 + tiles[id(node)] = _inset(box, pad), rgb * (1 - blend) + blend + + layout(nodes, rect) + # Draw leaves in input order; only layout needs size sorting. + for index, (node, label) in enumerate(zip(leaves, labels)): + (x, y, width, height), default_color = tiles[id(node)] + rgba = default_color if colors is None else colors[index % len(colors)] + leaf_style: dict[str, Any] = {"facecolor": rgba, **style} + patch = Rectangle((x, y), width, height, **leaf_style) + ax.add_patch(patch) + text = None + if label: + options = dict(text_style) + if isinstance(options["color"], str) and options["color"].lower() == "auto": + luminance = np.dot(patch.get_facecolor()[:3], [0.2126, 0.7152, 0.0722]) + options["color"] = "#18212b" if luminance > 0.5 else "white" + text = ax.text(x + width / 2, y + height / 2, label, **options) + text.set_clip_path(patch) result["patches"].append(patch) result["texts"].append(text) - result["paths"].append(node.path) - result["values"].append(node.value) ax.set_xlim(rect[0], rect[0] + rect[2]) ax.set_ylim(rect[1], rect[1] + rect[3]) ax.set_aspect("equal", adjustable="box") diff --git a/ultraplot/tests/test_treemap.py b/ultraplot/tests/test_treemap.py index 47c5b988b..44f5f7577 100644 --- a/ultraplot/tests/test_treemap.py +++ b/ultraplot/tests/test_treemap.py @@ -35,92 +35,78 @@ def _assert_tiling(patches, bounds): def test_treemap_proportional_area_and_no_overlap(rect): values = [3, 12, 1, 7, 2] fig, ax = uplt.subplots() - try: - result = ax.treemap(values, labels=list("ABCDE"), rect=rect, pad=0) - areas = [p.get_width() * p.get_height() for p in result["patches"]] - np.testing.assert_allclose( - areas, np.array(values) / sum(values) * rect[2] * rect[3] - ) - _assert_tiling(result["patches"], rect) - assert result["values"] == values - assert [text.get_text() for text in result["texts"]] == list("ABCDE") - fig.canvas.draw() - finally: - uplt.close(fig) + result = ax.treemap(values, labels=list("ABCDE"), rect=rect, pad=0) + areas = [p.get_width() * p.get_height() for p in result["patches"]] + np.testing.assert_allclose( + areas, np.array(values) / sum(values) * rect[2] * rect[3] + ) + _assert_tiling(result["patches"], rect) + assert result["values"] == values + assert [text.get_text() for text in result["texts"]] == list("ABCDE") + fig.canvas.draw() def test_treemap_hierarchy_preserves_totals_and_contains_descendants(): data = {"A": {"a": 4, "nested": {"b": 2, "c": 1}}, "B": {"d": 2}, "E": 1} fig, ax = uplt.subplots() - try: - result = ax.treemap(data, pad=0, group_pad=0, group_labels=False) - assert result["paths"] == [ - ("A", "a"), - ("A", "nested", "b"), - ("A", "nested", "c"), - ("B", "d"), - ("E",), - ] - np.testing.assert_allclose( - [p.get_width() * p.get_height() for p in result["patches"]], - np.array([4, 2, 1, 2, 1]) / 10, - ) - _assert_tiling(result["patches"], (0, 0, 1, 1)) - assert len(result["groups"]) == 3 - for group, prefix in zip(result["groups"], [("A",), ("A", "nested"), ("B",)]): - for patch, path in zip(result["patches"], result["paths"]): - if path[: len(prefix)] == prefix: - assert patch.get_x() >= group.get_x() - 1e-12 - assert patch.get_y() >= group.get_y() - 1e-12 - assert ( - patch.get_x() + patch.get_width() - <= group.get_x() + group.get_width() + 1e-12 - ) - assert ( - patch.get_y() + patch.get_height() - <= group.get_y() + group.get_height() + 1e-12 - ) - finally: - uplt.close(fig) + result = ax.treemap(data, pad=0, group_pad=0, group_labels=False) + assert result["paths"] == [ + ("A", "a"), + ("A", "nested", "b"), + ("A", "nested", "c"), + ("B", "d"), + ("E",), + ] + np.testing.assert_allclose( + [p.get_width() * p.get_height() for p in result["patches"]], + np.array([4, 2, 1, 2, 1]) / 10, + ) + _assert_tiling(result["patches"], (0, 0, 1, 1)) + assert len(result["groups"]) == 3 + for group, prefix in zip(result["groups"], [("A",), ("A", "nested"), ("B",)]): + for patch, path in zip(result["patches"], result["paths"]): + if path[: len(prefix)] == prefix: + assert patch.get_x() >= group.get_x() - 1e-12 + assert patch.get_y() >= group.get_y() - 1e-12 + assert ( + patch.get_x() + patch.get_width() + <= group.get_x() + group.get_width() + 1e-12 + ) + assert ( + patch.get_y() + patch.get_height() + <= group.get_y() + group.get_height() + 1e-12 + ) def test_treemap_colormap_colorbar_and_zero_alignment(): fig, ax = uplt.subplots() - try: - norm = Normalize(0, 8) - result = ax.treemap( - {"small": 1, "zero": 0, "large": 7}, cmap="viridis", norm=norm + norm = Normalize(0, 8) + result = ax.treemap({"small": 1, "zero": 0, "large": 7}, cmap="viridis", norm=norm) + assert result["paths"] == [("small",), ("large",)] + for patch, value in zip(result["patches"], [1, 7]): + np.testing.assert_allclose( + patch.get_facecolor(), result["mappable"].to_rgba(value) ) - assert result["paths"] == [("small",), ("large",)] - for patch, value in zip(result["patches"], [1, 7]): - np.testing.assert_allclose( - patch.get_facecolor(), result["mappable"].to_rgba(value) - ) - ax.colorbar(result["mappable"], label="Size") - fig.canvas.draw() - finally: - uplt.close(fig) + ax.colorbar(result["mappable"], label="Size") + fig.canvas.draw() def test_treemap_series_and_lookup_data(): fig, axs = uplt.subplots(ncols=2) - try: - series = pd.Series([1, 3], index=["A", "B"]) - result = axs[0].treemap(series, color=["red", "blue"]) - assert result["paths"] == [("A",), ("B",)] - for patch, color in zip(result["patches"], ["red", "blue"]): - np.testing.assert_allclose(patch.get_facecolor(), to_rgba(color)) - lookup = {"amount": [1, 3], "names": ["A", "B"]} - other = axs[1].treemap( - "amount", - labels="names", - data=lookup, - show_values=True, - value_format="{:.1f}", - ) - assert [text.get_text() for text in other["texts"]] == ["A\n1.0", "B\n3.0"] - finally: - uplt.close(fig) + series = pd.Series([1, 3], index=["A", "B"]) + result = axs[0].treemap(series, color=["red", "blue"]) + assert result["paths"] == [("A",), ("B",)] + for patch, color in zip(result["patches"], ["red", "blue"]): + np.testing.assert_allclose(patch.get_facecolor(), to_rgba(color)) + lookup = {"amount": [1, 3], "names": ["A", "B"]} + other = axs[1].treemap( + "amount", + labels="names", + data=lookup, + show_values=True, + value_format="{:.1f}", + ) + assert [text.get_text() for text in other["texts"]] == ["A\n1.0", "B\n3.0"] @pytest.mark.parametrize( @@ -143,13 +129,10 @@ def test_treemap_series_and_lookup_data(): def test_treemap_invalid_data_does_not_add_artists(sizes, kwargs): fig, ax = uplt.subplots() before = (list(ax.patches), list(ax.texts)) - try: - with pytest.raises(ValueError): - ax.treemap(sizes, **kwargs) - assert list(ax.patches) == before[0] - assert list(ax.texts) == before[1] - finally: - uplt.close(fig) + with pytest.raises(ValueError): + ax.treemap(sizes, **kwargs) + assert list(ax.patches) == before[0] + assert list(ax.texts) == before[1] def test_treemap_padding_and_styles_do_not_mutate_input(): @@ -157,19 +140,16 @@ def test_treemap_padding_and_styles_do_not_mutate_input(): text_kw = {"fontsize": 8} group_kw = {"lw": 2} fig, ax = uplt.subplots() - try: - result = ax.treemap( - data, pad=0.02, show_values=True, text_kw=text_kw, group_kw=group_kw, lw=1.5 - ) - assert text_kw == {"fontsize": 8} - assert group_kw == {"lw": 2} - assert data == {"Group": {"Alpha": 3, "Beta": 2}, "Other": 1} - assert all(p.get_linewidth() == 1.5 for p in result["patches"]) - assert result["groups"][0].get_linewidth() == 2 - assert all(text.get_clip_on() for text in result["texts"]) - fig.canvas.draw() - finally: - uplt.close(fig) + result = ax.treemap( + data, pad=0.02, show_values=True, text_kw=text_kw, group_kw=group_kw, lw=1.5 + ) + assert text_kw == {"fontsize": 8} + assert group_kw == {"lw": 2} + assert data == {"Group": {"Alpha": 3, "Beta": 2}, "Other": 1} + assert all(p.get_linewidth() == 1.5 for p in result["patches"]) + assert result["groups"][0].get_linewidth() == 2 + assert all(text.get_clip_on() for text in result["texts"]) + fig.canvas.draw() @pytest.mark.parametrize( @@ -178,15 +158,12 @@ def test_treemap_padding_and_styles_do_not_mutate_input(): def test_treemap_rejects_axes_that_distort_area(projection, scale): fig, axs = uplt.subplots(proj=projection) ax = axs[0] - try: - if scale is not None: - ax.set_xscale(scale) - before = list(ax.patches) - with pytest.raises(ValueError, match="Cartesian axes with linear scales"): - ax.treemap([1, 2]) - assert list(ax.patches) == before - finally: - uplt.close(fig) + if scale is not None: + ax.set_xscale(scale) + before = list(ax.patches) + with pytest.raises(ValueError, match="Cartesian axes with linear scales"): + ax.treemap([1, 2]) + assert list(ax.patches) == before def test_treemap_rc_layout_and_appearance() -> None: @@ -210,31 +187,28 @@ def test_treemap_rc_layout_and_appearance() -> None: before = {key: uplt.rc[key] for key in settings} fig, axs = uplt.subplots() ax = axs[0] - try: - with uplt.rc.context(settings): - result = ax.treemap({"Group": {"A": 3, "B": 1}}) - assert {key: uplt.rc[key] for key in settings} == before - np.testing.assert_allclose(ax.get_xlim(), [2, 4]) - np.testing.assert_allclose(ax.get_ylim(), [3, 4]) - assert [text.get_text() for text in result["texts"]] == [ - "A\n3.0 kg", - "B\n1.0 kg", - ] - for patch, text in zip(result["patches"], result["texts"]): - assert patch.get_linewidth() == 2 - np.testing.assert_allclose(patch.get_edgecolor(), to_rgba("navy")) - assert text.get_fontsize() == 12 - assert text.get_color() == "purple" - group = result["groups"][0] - assert group.get_alpha() == 0.4 - assert group.get_linewidth() == 3 - np.testing.assert_allclose(group.get_edgecolor(), to_rgba("red", 0.4)) - header = result["group_texts"][0] - assert header.get_fontsize() == 14 - assert header.get_fontweight() == "normal" - fig.canvas.draw() - finally: - uplt.close(fig) + with uplt.rc.context(settings): + result = ax.treemap({"Group": {"A": 3, "B": 1}}) + assert {key: uplt.rc[key] for key in settings} == before + np.testing.assert_allclose(ax.get_xlim(), [2, 4]) + np.testing.assert_allclose(ax.get_ylim(), [3, 4]) + assert [text.get_text() for text in result["texts"]] == [ + "A\n3.0 kg", + "B\n1.0 kg", + ] + for patch, text in zip(result["patches"], result["texts"]): + assert patch.get_linewidth() == 2 + np.testing.assert_allclose(patch.get_edgecolor(), to_rgba("navy")) + assert text.get_fontsize() == 12 + assert text.get_color() == "purple" + group = result["groups"][0] + assert group.get_alpha() == 0.4 + assert group.get_linewidth() == 3 + np.testing.assert_allclose(group.get_edgecolor(), to_rgba("red", 0.4)) + header = result["group_texts"][0] + assert header.get_fontsize() == 14 + assert header.get_fontweight() == "normal" + fig.canvas.draw() def test_treemap_explicit_options_and_aliases_override_rc() -> None: @@ -250,29 +224,26 @@ def test_treemap_explicit_options_and_aliases_override_rc() -> None: "treemap.text.size": 20, } fig, ax = uplt.subplots() - try: - with uplt.rc.context(settings): - result = ax.treemap( - {"Group": {"A": 3, "B": 1}}, - rect=(0, 0, 1, 1), - pad=0, - group_pad=0, - group_labels=False, - show_values=False, - lw=0, - text_kw={"c": "navy", "size": 8}, - group_kw={"a": 0, "lw": 0}, - ) - _assert_tiling(result["patches"], (0, 0, 1, 1)) - assert not result["group_texts"] - assert [text.get_text() for text in result["texts"]] == ["A", "B"] - assert all(p.get_linewidth() == 0 for p in result["patches"]) - assert all(text.get_color() == "navy" for text in result["texts"]) - assert all(text.get_fontsize() == 8 for text in result["texts"]) - assert result["groups"][0].get_alpha() == 0 - assert result["groups"][0].get_linewidth() == 0 - finally: - uplt.close(fig) + with uplt.rc.context(settings): + result = ax.treemap( + {"Group": {"A": 3, "B": 1}}, + rect=(0, 0, 1, 1), + pad=0, + group_pad=0, + group_labels=False, + show_values=False, + lw=0, + text_kw={"c": "navy", "size": 8}, + group_kw={"a": 0, "lw": 0}, + ) + _assert_tiling(result["patches"], (0, 0, 1, 1)) + assert not result["group_texts"] + assert [text.get_text() for text in result["texts"]] == ["A", "B"] + assert all(p.get_linewidth() == 0 for p in result["patches"]) + assert all(text.get_color() == "navy" for text in result["texts"]) + assert all(text.get_fontsize() == 8 for text in result["texts"]) + assert result["groups"][0].get_alpha() == 0 + assert result["groups"][0].get_linewidth() == 0 def test_treemap_rc_file_and_context_restore(tmp_path: Path) -> None: @@ -288,33 +259,27 @@ def test_treemap_rc_file_and_context_restore(tmp_path: Path) -> None: before = uplt.rc["treemap.rect"] fig, axs = uplt.subplots() ax = axs[0] - try: - with uplt.rc.context(file=str(path)): - result = ax.treemap({"A": 3, "B": 1}) - assert uplt.rc["treemap.rect"] == (1, 2, 3, 4) - assert uplt.rc["treemap.rect"] == before - _assert_tiling(result["patches"], (1, 2, 3, 4)) - assert result["texts"][0].get_text() == "A\n3.0" - assert result["texts"][0].get_color() == "navy" - finally: - uplt.close(fig) + with uplt.rc.context(file=str(path)): + result = ax.treemap({"A": 3, "B": 1}) + assert uplt.rc["treemap.rect"] == (1, 2, 3, 4) + assert uplt.rc["treemap.rect"] == before + _assert_tiling(result["patches"], (1, 2, 3, 4)) + assert result["texts"][0].get_text() == "A\n3.0" + assert result["texts"][0].get_color() == "navy" def test_treemap_callable_rc_formatter_and_call_override() -> None: fig, axs = uplt.subplots(ncols=2) - try: - with uplt.rc.context( - { - "treemap.value_format": lambda value: f"{value:.0f}kg", - "treemap.show_values": True, - } - ): - first = axs[0].treemap([3], labels=["A"]) - second = axs[1].treemap([3], labels=["A"], value_format="{:.1f}") - assert first["texts"][0].get_text() == "A\n3kg" - assert second["texts"][0].get_text() == "A\n3.0" - finally: - uplt.close(fig) + with uplt.rc.context( + { + "treemap.value_format": lambda value: f"{value:.0f}kg", + "treemap.show_values": True, + } + ): + first = axs[0].treemap([3], labels=["A"]) + second = axs[1].treemap([3], labels=["A"], value_format="{:.1f}") + assert first["texts"][0].get_text() == "A\n3kg" + assert second["texts"][0].get_text() == "A\n3.0" @pytest.mark.parametrize( @@ -338,32 +303,27 @@ def test_treemap_rc_rejects_invalid_settings(key: str, value: object) -> None: def test_treemap_defaults_match_original_appearance() -> None: fig, axs = uplt.subplots(ncols=2) data = {"Group": {"A": 3, "B": 1}, "Other": 2} - try: - default = axs[0].treemap(data) - explicit = axs[1].treemap( - data, - rect=(0, 0, 1, 1), - pad=0.008, - group_pad=0.018, - group_labels=True, - show_values=False, - value_format="{:g}", - ec="white", - lw=0.6, - text_kw={"fontsize": 9}, - group_kw={"ec": "white", "lw": 1.2, "alpha": 0.12}, - ) - for key in ("patches", "groups"): - for actual, expected in zip(default[key], explicit[key]): - np.testing.assert_allclose( - actual.get_bbox().bounds, expected.get_bbox().bounds - ) - np.testing.assert_allclose( - actual.get_facecolor(), expected.get_facecolor() - ) - assert actual.get_linewidth() == expected.get_linewidth() - for actual, expected in zip(default["texts"], explicit["texts"]): - assert actual.get_fontsize() == expected.get_fontsize() - assert actual.get_color() == expected.get_color() - finally: - uplt.close(fig) + default = axs[0].treemap(data) + explicit = axs[1].treemap( + data, + rect=(0, 0, 1, 1), + pad=0.008, + group_pad=0.018, + group_labels=True, + show_values=False, + value_format="{:g}", + ec="white", + lw=0.6, + text_kw={"fontsize": 9}, + group_kw={"ec": "white", "lw": 1.2, "alpha": 0.12}, + ) + for key in ("patches", "groups"): + for actual, expected in zip(default[key], explicit[key]): + np.testing.assert_allclose( + actual.get_bbox().bounds, expected.get_bbox().bounds + ) + np.testing.assert_allclose(actual.get_facecolor(), expected.get_facecolor()) + assert actual.get_linewidth() == expected.get_linewidth() + for actual, expected in zip(default["texts"], explicit["texts"]): + assert actual.get_fontsize() == expected.get_fontsize() + assert actual.get_color() == expected.get_color() From 6f99b7d599ec89c035df83275c5343b8a3f74b22 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Tue, 3 Nov 2026 20:12:22 +1000 Subject: [PATCH 04/11] Compact treemap gallery example using shared rc settings --- docs/examples/plot_types/14_treemap.py | 32 +++++++++----------------- 1 file changed, 11 insertions(+), 21 deletions(-) diff --git a/docs/examples/plot_types/14_treemap.py b/docs/examples/plot_types/14_treemap.py index 76eb040ae..7bef3329e 100644 --- a/docs/examples/plot_types/14_treemap.py +++ b/docs/examples/plot_types/14_treemap.py @@ -9,30 +9,20 @@ import ultraplot as uplt +energy = {"Solar": 36, "Wind": 28, "Hydro": 18, "Nuclear": 12, "Other": 6} +colors = ["#3c8d87", "#5286b0", "#69a4b7", "#af8a55", "#959baa"] +budget = { + "Research": {"Fieldwork": 24, "Equipment": 16, "Data": 10}, + "People": {"Staff": 20, "Training": 10}, + "Operations": {"Travel": 12, "Services": 8}, +} + fig, axs = uplt.subplots(ncols=2, refwidth=4.2, refaspect=1, share=False) +with uplt.rc.context({"treemap.show_values": True, "treemap.pad": 0.012}): + axs[0].treemap(energy, color=colors, value_format="{:.0f}%", text_kw={"size": 11}) + axs[1].treemap(budget, text_kw={"size": 10}) -axs[0].treemap( - {"Solar": 36, "Wind": 28, "Hydro": 18, "Nuclear": 12, "Other": 6}, - color=["#3c8d87", "#5286b0", "#69a4b7", "#af8a55", "#959baa"], - show_values=True, - value_format="{:.0f}%", - pad=0.012, - text_kw={"fontsize": 11}, -) axs[0].format(title="Flat categories") - -axs[1].treemap( - { - "Research": {"Fieldwork": 24, "Equipment": 16, "Data": 10}, - "People": {"Staff": 20, "Training": 10}, - "Operations": {"Travel": 12, "Services": 8}, - }, - show_values=True, - value_format="{:.0f}", - pad=0.012, - group_pad=0.018, - text_kw={"fontsize": 10}, -) axs[1].format(title="Nested categories") axs.format(suptitle="Treemaps · area shows value") fig.show() From 06ce5bd69ac867d881d941664c4313f801a3e399 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 12 Nov 2026 20:35:09 +1000 Subject: [PATCH 05/11] Reuse shared color handling for treemaps --- ultraplot/axes/plot.py | 22 +++++--- ultraplot/axes/plot_types/treemap.py | 30 +++++++---- ultraplot/tests/test_treemap.py | 76 ++++++++++++++++++++++++++-- 3 files changed, 107 insertions(+), 21 deletions(-) diff --git a/ultraplot/axes/plot.py b/ultraplot/axes/plot.py index 3a6d0b6e6..48b4f20cf 100644 --- a/ultraplot/axes/plot.py +++ b/ultraplot/axes/plot.py @@ -6800,16 +6800,22 @@ def treemap( Nonnegative tile sizes. Zero-sized leaves are omitted. A mapping supplies labels from its keys; nested mappings define groups, whose areas are proportional to the sum of their descendants. A Series - supplies labels from its index. Values must be finite, with at - least one positive value in each group. No extra package is needed. - labels : sequence of str, optional - Labels for a flat sequence, in input order. - data : mapping, optional + supplies labels from its index unless ``labels`` is given. Values + must be finite, with at least one positive value in each group. + No extra package is needed. + labels : sequence of str or str, optional + Labels for a flat sequence, in input order, or a column name in ``data``. + data : mapping or pandas.DataFrame, optional Look up string ``sizes`` and ``labels`` arguments in this object. - color : color or sequence of colors, optional - A single color or one color per nonzero leaf in input order. + color, colors, c : color or sequence of colors, optional + Colors for nonzero leaves in input order, repeated as needed. By default, top-level categories use the current cycle, and leaves within a group share shades of the group's color. + cycle : cycle-spec, optional + Property cycle for top-level categories, assigned in input order. + Uses the axes' current patch cycle by default. + cycle_kw : dict, optional + Keyword arguments passed to `~ultraplot.constructor.Cycle`. cmap : colormap, optional Color leaves by size. Mutually exclusive with ``color``. norm : matplotlib.colors.Normalize, optional @@ -6850,6 +6856,8 @@ def treemap( >>> fig, ax = uplt.subplots() >>> artists = ax.treemap({'A': 6, 'B': 3, 'C': 1}, show_values=True) >>> artists = ax.treemap({'Group': {'A': 6, 'B': 3}, 'Other': 1}) + >>> data = {'amount': [2, 3, 4], 'name': ['A', 'B', 'C']} + >>> artists = ax.treemap('amount', labels='name', data=data, colors=['r', 'g']) """ from .plot_types.treemap import treemap diff --git a/ultraplot/axes/plot_types/treemap.py b/ultraplot/axes/plot_types/treemap.py index 9ee7f1e34..e620ac6eb 100644 --- a/ultraplot/axes/plot_types/treemap.py +++ b/ultraplot/axes/plot_types/treemap.py @@ -74,10 +74,10 @@ def _nodes( ) -> list[_Node]: """Validate the complete hierarchy before adding any artists.""" if isinstance(sizes, Mapping) or ( - getattr(sizes, "ndim", None) == 1 and hasattr(sizes, "items") + labels is None and getattr(sizes, "ndim", None) == 1 and hasattr(sizes, "items") ): if labels is not None: - raise ValueError("Mapping and Series inputs already supply their labels.") + raise ValueError("Mapping inputs already supply their labels.") result = [] # Series is duck-typed so pandas remains an optional dependency. for key, value in cast(Mapping[Hashable, Any], sizes).items(): @@ -211,6 +211,8 @@ def treemap( if not ax.transData.is_affine: raise ValueError("treemap requires Cartesian axes with linear scales.") nodes = _nodes(sizes, labels) + style = _style("patch", "patch", kwargs) + color = _not_none(color=color, colors=style.pop("color", None)) if color is not None and cmap is not None: raise ValueError("Use either color or cmap, not both.") leaves = [leaf for node in nodes for leaf in node.leaves()] @@ -228,15 +230,10 @@ def treemap( colors = mappable.to_rgba(values) elif color is not None: colors = mcolors.to_rgba_array(color) - if len(colors) not in (1, len(leaves)): - raise ValueError( - "color must be a single color or one color per nonzero leaf." - ) + if len(colors) == 0: + raise ValueError("color must contain at least one color.") elif norm is not None or vmin is not None or vmax is not None: raise ValueError("norm, vmin, and vmax require cmap.") - cycle = constructor.Cycle(rc["cycle"]).by_key()["color"] - - style = _style("patch", "patch", kwargs) parent_style = _style("group", "patch", group_kw) text_style: dict[str, Any] = { "ha": "center", @@ -256,6 +253,8 @@ def treemap( for node in leaves ] + style = ax._parse_cycle(sum(node.value > 0 for node in nodes), **style) + result: TreemapResult = { "patches": [], "texts": [], @@ -270,8 +269,17 @@ def treemap( def layout( branch: Sequence[_Node], bounds: Bounds, base_color: TreemapColor | None = None ) -> None: - for index, (node, box) in enumerate(_squarify(branch, bounds)): - hue = base_color if base_color is not None else cycle[index % len(cycle)] + # Sorting determines positions only. Assign colors in input order. + boxes = {id(node): box for node, box in _squarify(branch, bounds)} + for index, node in enumerate(node for node in branch if node.value > 0): + box = boxes[id(node)] + hue = base_color + if hue is None: + hue = ( + ax._get_patches_for_fill.get_next_color() + if colors is None or node.children + else "none" + ) if node.children: box = _inset(box, group_pad) x, y, width, height = box diff --git a/ultraplot/tests/test_treemap.py b/ultraplot/tests/test_treemap.py index 44f5f7577..2c7353f27 100644 --- a/ultraplot/tests/test_treemap.py +++ b/ultraplot/tests/test_treemap.py @@ -91,14 +91,15 @@ def test_treemap_colormap_colorbar_and_zero_alignment(): fig.canvas.draw() -def test_treemap_series_and_lookup_data(): +@pytest.mark.parametrize("container", [dict, pd.DataFrame]) +def test_treemap_series_and_lookup_data(container): fig, axs = uplt.subplots(ncols=2) series = pd.Series([1, 3], index=["A", "B"]) result = axs[0].treemap(series, color=["red", "blue"]) assert result["paths"] == [("A",), ("B",)] for patch, color in zip(result["patches"], ["red", "blue"]): np.testing.assert_allclose(patch.get_facecolor(), to_rgba(color)) - lookup = {"amount": [1, 3], "names": ["A", "B"]} + lookup = container({"amount": [1, 3], "names": ["A", "B"]}) other = axs[1].treemap( "amount", labels="names", @@ -109,6 +110,74 @@ def test_treemap_series_and_lookup_data(): assert [text.get_text() for text in other["texts"]] == ["A\n1.0", "B\n3.0"] +@pytest.mark.parametrize("keyword", ["color", "colors", "c"]) +@pytest.mark.parametrize("palette", [["r"], ["r", "g"], ["r", "g", "b", "k", "y"]]) +def test_treemap_palette_cycles_in_input_order(keyword, palette): + _, ax = uplt.subplots() + result = ax.treemap( + {"GroupA": {"a": 2, "zero": 0, "b": 3}, "GroupB": {"c": 4, "d": 5}}, + **{keyword: palette}, + ) + assert result["paths"] == [ + ("GroupA", "a"), + ("GroupA", "b"), + ("GroupB", "c"), + ("GroupB", "d"), + ] + for index, patch in enumerate(result["patches"]): + np.testing.assert_allclose( + patch.get_facecolor(), to_rgba(palette[index % len(palette)]) + ) + + +def test_treemap_uses_current_patch_cycle_and_advances(): + _, ax = uplt.subplots() + ax.set_prop_cycle(color=["r", "g", "b", "k"]) + ax.bar([0], [1]) + result = ax.treemap({"a": 2, "zero": 0, "b": 3}) + for patch, color in zip(result["patches"], ["g", "b"]): + np.testing.assert_allclose(patch.get_facecolor(), to_rgba(color)) + following = ax.treemap([1]) + np.testing.assert_allclose(following["patches"][0].get_facecolor(), to_rgba("k")) + + +@pytest.mark.parametrize("kwargs", [{"color": "r"}, {"cmap": "viridis"}]) +def test_treemap_explicit_leaf_colors_do_not_advance_cycle(kwargs): + _, ax = uplt.subplots() + ax.set_prop_cycle(color=["g", "b"]) + ax.treemap([1, 2], **kwargs) + result = ax.treemap([1]) + np.testing.assert_allclose(result["patches"][0].get_facecolor(), to_rgba("g")) + + +def test_treemap_group_colors_do_not_depend_on_size_sorting(): + _, axs = uplt.subplots(ncols=2) + first = axs[0].treemap( + {"A": {"a": 1, "b": 2}, "B": {"c": 3, "d": 4}}, cycle=["r", "g"] + ) + second = axs[1].treemap( + {"A": {"a": 4, "b": 3}, "B": {"c": 2, "d": 1}}, cycle=["r", "g"] + ) + for key in ("patches", "groups"): + np.testing.assert_allclose( + [p.get_facecolor() for p in first[key]], + [p.get_facecolor() for p in second[key]], + ) + np.testing.assert_allclose(first["groups"][0].get_facecolor()[:3], to_rgba("r")[:3]) + np.testing.assert_allclose(first["groups"][1].get_facecolor()[:3], to_rgba("g")[:3]) + + +def test_treemap_named_cycle_and_cycle_options(): + _, ax = uplt.subplots() + options = {"reverse": True} + result = ax.treemap([1, 0, 3, 2], cycle="colorblind", cycle_kw=options) + expected = uplt.Cycle("colorblind", N=3, reverse=True).by_key()["color"] + np.testing.assert_allclose( + [p.get_facecolor() for p in result["patches"]], + [to_rgba(color) for color in expected], + ) + + @pytest.mark.parametrize( "sizes,kwargs", [ @@ -123,7 +192,8 @@ def test_treemap_series_and_lookup_data(): ([1], {"pad": -1}), ([1], {"rect": (0, 0, 0, 1)}), ([1], {"color": "red", "cmap": "viridis"}), - ([1, 2], {"color": ["red", "blue", "green"]}), + ([1, 2], {"color": []}), + ([1], {"colors": ["r", "g"], "cmap": "viridis"}), ], ) def test_treemap_invalid_data_does_not_add_artists(sizes, kwargs): From 60d0f91cd6fbad105c604c973722d4427a41a8e0 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 13 Nov 2026 05:35:53 +1000 Subject: [PATCH 06/11] Align treemap labels with literal label semantics --- ultraplot/axes/plot.py | 11 +++++++---- ultraplot/axes/plot_types/treemap.py | 4 +++- ultraplot/tests/test_treemap.py | 22 +++++++++++++++++++++- 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/ultraplot/axes/plot.py b/ultraplot/axes/plot.py index ec96d9960..d3666b784 100644 --- a/ultraplot/axes/plot.py +++ b/ultraplot/axes/plot.py @@ -6824,9 +6824,11 @@ def treemap( must be finite, with at least one positive value in each group. No extra package is needed. labels : sequence of str or str, optional - Labels for a flat sequence, in input order, or a column name in ``data``. + Labels for a flat sequence, in input order. A string is literal + text repeated for each tile, even when ``data`` is provided. + Pass column values explicitly, for example ``labels=df['name']``. data : mapping or pandas.DataFrame, optional - Look up string ``sizes`` and ``labels`` arguments in this object. + Look up a string ``sizes`` argument in this object. color, colors, c : color or sequence of colors, optional Colors for nonzero leaves in input order, repeated as needed. By default, top-level categories use the current cycle, and leaves @@ -6877,12 +6879,13 @@ def treemap( >>> artists = ax.treemap({'A': 6, 'B': 3, 'C': 1}, show_values=True) >>> artists = ax.treemap({'Group': {'A': 6, 'B': 3}, 'Other': 1}) >>> data = {'amount': [2, 3, 4], 'name': ['A', 'B', 'C']} - >>> artists = ax.treemap('amount', labels='name', data=data, colors=['r', 'g']) + >>> artists = ax.treemap('amount', labels=data['name'], data=data) + >>> artists = ax.treemap([2, 3, 4], labels='Category') """ from .plot_types.treemap import treemap if data is not None: - sizes, labels = inputs._from_data(data, sizes, labels) + sizes, _ = inputs._from_data(data, sizes, None) return treemap( self, sizes, diff --git a/ultraplot/axes/plot_types/treemap.py b/ultraplot/axes/plot_types/treemap.py index e620ac6eb..31d590d5f 100644 --- a/ultraplot/axes/plot_types/treemap.py +++ b/ultraplot/axes/plot_types/treemap.py @@ -101,7 +101,9 @@ def _nodes( raise ValueError("sizes must be a one-dimensional numeric sequence.") if labels is None: labels = [""] * len(values) - elif isinstance(labels, str) or len(labels) != len(values): + elif isinstance(labels, str): + labels = [labels] * len(values) + if len(labels) != len(values): raise ValueError("labels must have the same length as sizes.") result = [ _Node(str(label), _validate_nonnegative_float(value), (index,)) diff --git a/ultraplot/tests/test_treemap.py b/ultraplot/tests/test_treemap.py index 2c7353f27..1ad6e447c 100644 --- a/ultraplot/tests/test_treemap.py +++ b/ultraplot/tests/test_treemap.py @@ -102,7 +102,7 @@ def test_treemap_series_and_lookup_data(container): lookup = container({"amount": [1, 3], "names": ["A", "B"]}) other = axs[1].treemap( "amount", - labels="names", + labels=lookup["names"], data=lookup, show_values=True, value_format="{:.1f}", @@ -110,6 +110,26 @@ def test_treemap_series_and_lookup_data(container): assert [text.get_text() for text in other["texts"]] == ["A\n1.0", "B\n3.0"] +@pytest.mark.parametrize("container", [dict, pd.DataFrame]) +@pytest.mark.parametrize("lookup_sizes", [False, True]) +def test_treemap_string_labels_are_literal_with_data(container, lookup_sizes): + _, ax = uplt.subplots() + data = container({"amount": [2, 0, 3], "name": ["A", "B", "C"]}) + sizes = "amount" if lookup_sizes else data["amount"] + result = ax.treemap(sizes, labels="name", data=data) + assert [text.get_text() for text in result["texts"]] == ["name", "name"] + assert result["values"] == [2, 3] + + +def test_treemap_string_labels_repeat_without_data(): + _, ax = uplt.subplots() + result = ax.treemap([2, 0, 3], labels="Category", show_values=True) + assert [text.get_text() for text in result["texts"]] == [ + "Category\n2", + "Category\n3", + ] + + @pytest.mark.parametrize("keyword", ["color", "colors", "c"]) @pytest.mark.parametrize("palette", [["r"], ["r", "g"], ["r", "g", "b", "k", "y"]]) def test_treemap_palette_cycles_in_input_order(keyword, palette): From f24a3fe3aa56b49b2ff8ed562bfb90adcc6ce714 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 19 Nov 2026 09:59:15 +0100 Subject: [PATCH 07/11] Stabilize treemap strip sizing and validate color options --- ultraplot/axes/plot_types/treemap.py | 86 +++++++++++++++------------- ultraplot/tests/test_treemap.py | 19 ++++++ 2 files changed, 66 insertions(+), 39 deletions(-) diff --git a/ultraplot/axes/plot_types/treemap.py b/ultraplot/axes/plot_types/treemap.py index 31d590d5f..3d4d51ef5 100644 --- a/ultraplot/axes/plot_types/treemap.py +++ b/ultraplot/axes/plot_types/treemap.py @@ -120,46 +120,53 @@ def _squarify(nodes: Sequence[_Node], rect: Bounds) -> list[tuple[_Node, Bounds] ordered = sorted((node for node in nodes if node.value > 0), key=lambda n: -n.value) scale = max(node.value for node in ordered) weights = [node.value / scale for node in ordered] - total = math.fsum(weights) - areas = [weight / total * width * height for weight in weights] - result: list[tuple[_Node, Bounds]] = [] + # Use fractions of the remaining rectangle so rounding in a large strip + # cannot inflate the dimensions of a much smaller tile that follows it. + remaining = [0.0] * (len(weights) + 1) + for i in reversed(range(len(weights))): + remaining[i] = remaining[i + 1] + weights[i] - def worst(row: list[tuple[_Node, float]], side: float) -> float: - total = math.fsum(area for _, area in row) - smallest = min(area for _, area in row) - largest = max(area for _, area in row) - return max( - side * side * largest / total**2, total**2 / (side * side * smallest) - ) - - def place(row: list[tuple[_Node, float]], bounds: Bounds) -> Bounds: - x, y, width, height = bounds - area = math.fsum(size for _, size in row) + result: list[tuple[_Node, Bounds]] = [] + start = 0 + while start < len(ordered): vertical = width >= height - strip = area / min(width, height) + long, short = (width, height) if vertical else (height, width) + total = remaining[start] + if total == 0 or short == 0: + result.extend((node, (x, y, 0.0, 0.0)) for node in ordered[start:]) + break + + def worst(weight: float, smallest: float) -> float: + strip = long * (weight / total) + narrow = short * (smallest / weight) + wide = short * (weights[start] / weight) + return max(wide / strip, strip / narrow) if strip and narrow else math.inf + + end = start + 1 + weight = weights[start] + score = worst(weight, weight) + while end < len(ordered) and weights[end] > 0: + candidate = weight + weights[end] + next_score = worst(candidate, weights[end]) + if next_score > score: + break + weight, score = candidate, next_score + end += 1 + + strip = long * min(1.0, weight / total) offset = y if vertical else x - for node, size in row: - length = size / strip + for i in range(start, end): + length = short * (weights[i] / weight) box = (x, offset, strip, length) if vertical else (offset, y, length, strip) - result.append((node, box)) + result.append((ordered[i], box)) offset += length - return ( - (x + strip, y, max(0, width - strip), height) - if vertical - else (x, y + strip, width, max(0, height - strip)) - ) - - row: list[tuple[_Node, float]] = [] - for node, area in zip(ordered, areas): - candidate = [*row, (node, area)] - if row and worst(candidate, min(width, height)) > worst( - row, min(width, height) - ): - x, y, width, height = place(row, (x, y, width, height)) - row = [] - row.append((node, area)) - if row: - place(row, (x, y, width, height)) + if vertical: + x += strip + width = long * (remaining[end] / total) + else: + y += strip + height = long * (remaining[end] / total) + start = end return result @@ -221,6 +228,8 @@ def treemap( values = np.array([node.value for node in leaves]) mappable: mcm.ScalarMappable | None = None colors: NDArray[np.float64] | None = None + if cmap is None and any(option is not None for option in (norm, vmin, vmax)): + raise ValueError("norm, vmin, and vmax require cmap.") if cmap is not None: if norm is None: norm = mcolors.Normalize(vmin=vmin, vmax=vmax) @@ -234,8 +243,6 @@ def treemap( colors = mcolors.to_rgba_array(color) if len(colors) == 0: raise ValueError("color must contain at least one color.") - elif norm is not None or vmin is not None or vmax is not None: - raise ValueError("norm, vmin, and vmax require cmap.") parent_style = _style("group", "patch", group_kw) text_style: dict[str, Any] = { "ha": "center", @@ -302,9 +309,10 @@ def layout( result["group_texts"].append(label) layout(node.children, (*inner[:3], inner[3] - header), hue) else: - rgb = np.array(mcolors.to_rgb(hue)) + rgba = np.array(mcolors.to_rgba(hue)) blend = 0.10 + 0.12 * (index % 4) if base_color is not None else 0 - tiles[id(node)] = _inset(box, pad), rgb * (1 - blend) + blend + rgba[:3] = rgba[:3] * (1 - blend) + blend + tiles[id(node)] = _inset(box, pad), rgba layout(nodes, rect) # Draw leaves in input order; only layout needs size sorting. diff --git a/ultraplot/tests/test_treemap.py b/ultraplot/tests/test_treemap.py index 1ad6e447c..a0116fe4d 100644 --- a/ultraplot/tests/test_treemap.py +++ b/ultraplot/tests/test_treemap.py @@ -213,6 +213,9 @@ def test_treemap_named_cycle_and_cycle_options(): ([1], {"rect": (0, 0, 0, 1)}), ([1], {"color": "red", "cmap": "viridis"}), ([1, 2], {"color": []}), + ([1], {"colors": ["r"], "vmin": 0}), + ([1], {"color": "red", "vmax": 10}), + ([1], {"color": "red", "norm": Normalize()}), ([1], {"colors": ["r", "g"], "cmap": "viridis"}), ], ) @@ -417,3 +420,19 @@ def test_treemap_defaults_match_original_appearance() -> None: for actual, expected in zip(default["texts"], explicit["texts"]): assert actual.get_fontsize() == expected.get_fontsize() assert actual.get_color() == expected.get_color() + + +def test_treemap_preserves_patch_cycle_alpha(): + _, ax = uplt.subplots() + ax.set_prop_cycle(color=[(0.2, 0.4, 0.6, 0.5)]) + result = ax.treemap({"A": {"a": 1}, "B": 2}) + assert [patch.get_facecolor()[3] for patch in result["patches"]] == [0.5, 0.5] + + +def test_treemap_extreme_size_range(): + _, ax = uplt.subplots() + result = ax.treemap([1e200, 1, 1e-200], pad=0) + assert result["values"] == [1e200, 1, 1e-200] + middle = result["patches"][1] + assert middle.get_width() * middle.get_height() == pytest.approx(1e-200, abs=0) + _assert_tiling(result["patches"], (0, 0, 1, 1)) From 0439ddff0e81a1f5efab710e23715aea469d20b2 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 19 Nov 2026 10:10:30 +0100 Subject: [PATCH 08/11] Handle transparent treemaps, failed draws, and overflowing group totals --- ultraplot/axes/plot_types/treemap.py | 113 ++++++++++++++++++++------- ultraplot/tests/test_treemap.py | 51 ++++++++++++ 2 files changed, 135 insertions(+), 29 deletions(-) diff --git a/ultraplot/axes/plot_types/treemap.py b/ultraplot/axes/plot_types/treemap.py index 3d4d51ef5..6ed84ec36 100644 --- a/ultraplot/axes/plot_types/treemap.py +++ b/ultraplot/axes/plot_types/treemap.py @@ -3,7 +3,10 @@ from __future__ import annotations from collections.abc import Callable, Hashable, Iterator, Mapping, Sequence +from contextlib import contextmanager +from copy import copy from dataclasses import dataclass +from fractions import Fraction import math from typing import TYPE_CHECKING, Any, TypeAlias, TypedDict, Union, cast @@ -55,7 +58,7 @@ class TreemapResult(TypedDict): @dataclass class _Node: label: str - value: float + value: float | Fraction path: NodePath children: tuple[_Node, ...] = () @@ -84,7 +87,12 @@ def _nodes( child_path = (*path, key) if isinstance(value, Mapping): children = _nodes(cast(TreemapHierarchy, value), path=child_path) - total = math.fsum(child.value for child in children) + try: + total = math.fsum(child.value for child in children) + except OverflowError: + # Only group totals can exceed float range. Preserve leaf + # values for labels, formatting, and colormap normalization. + total = sum(Fraction(child.value) for child in children) result.append(_Node(str(key), total, child_path, tuple(children))) else: result.append( @@ -119,7 +127,10 @@ def _squarify(nodes: Sequence[_Node], rect: Bounds) -> list[tuple[_Node, Bounds] x, y, width, height = rect ordered = sorted((node for node in nodes if node.value > 0), key=lambda n: -n.value) scale = max(node.value for node in ordered) - weights = [node.value / scale for node in ordered] + if isinstance(scale, Fraction): + weights = [float(Fraction(node.value) / scale) for node in ordered] + else: + weights = [node.value / scale for node in ordered] # Use fractions of the remaining rectangle so rounding in a large strip # cannot inflate the dimensions of a much smaller tile that follows it. remaining = [0.0] * (len(weights) + 1) @@ -186,6 +197,34 @@ def _style( return {**_pop_props(defaults, kind), **props} +def _composite(foreground, background): + rgb = np.asarray(foreground[:3]) + alpha = foreground[3] + return rgb * alpha + background * (1 - alpha) + + +@contextmanager +def _draw_transaction(ax): + """Restore artists, data bounds, and cycle positions if a style fails.""" + existing = set(ax.get_children()) + bounds = ax.dataLim.frozen() + ignore_limits = ax.ignore_existing_data_limits + cycles = ax._active_cycle, copy(ax._get_lines), copy(ax._get_patches_for_fill) + try: + yield + except Exception: + for artist in reversed(ax.get_children()): + if artist not in existing: + if isinstance(artist, Text): + ax._register_align_text(artist, False) + artist.remove() + ax.dataLim.set(bounds) + ax.dataLim.minpos[:] = bounds.minpos + ax.ignore_existing_data_limits = ignore_limits + ax._active_cycle, ax._get_lines, ax._get_patches_for_fill = cycles + raise + + def treemap( ax: PlotAxes, sizes: TreemapInput, @@ -240,7 +279,7 @@ def treemap( mappable.autoscale_None() colors = mappable.to_rgba(values) elif color is not None: - colors = mcolors.to_rgba_array(color) + colors = mcolors.to_rgba_array([color] if isinstance(color, str) else color) if len(colors) == 0: raise ValueError("color must contain at least one color.") parent_style = _style("group", "patch", group_kw) @@ -262,8 +301,6 @@ def treemap( for node in leaves ] - style = ax._parse_cycle(sum(node.value > 0 for node in nodes), **style) - result: TreemapResult = { "patches": [], "texts": [], @@ -273,10 +310,13 @@ def treemap( "values": values.tolist(), "mappable": mappable, } - tiles: dict[int, tuple[Bounds, NDArray[np.float64]]] = {} + tiles: dict[int, tuple[Bounds, NDArray[np.float64], NDArray[np.float64]]] = {} def layout( - branch: Sequence[_Node], bounds: Bounds, base_color: TreemapColor | None = None + branch: Sequence[_Node], + bounds: Bounds, + background: NDArray[np.float64], + base_color: TreemapColor | None = None, ) -> None: # Sorting determines positions only. Assign colors in input order. boxes = {id(node): box for node, box in _squarify(branch, bounds)} @@ -307,31 +347,46 @@ def layout( ) label.set_clip_path(patch) result["group_texts"].append(label) - layout(node.children, (*inner[:3], inner[3] - header), hue) + layout( + node.children, + (*inner[:3], inner[3] - header), + _composite(patch.get_facecolor(), background), + hue, + ) else: rgba = np.array(mcolors.to_rgba(hue)) blend = 0.10 + 0.12 * (index % 4) if base_color is not None else 0 rgba[:3] = rgba[:3] * (1 - blend) + blend - tiles[id(node)] = _inset(box, pad), rgba - - layout(nodes, rect) - # Draw leaves in input order; only layout needs size sorting. - for index, (node, label) in enumerate(zip(leaves, labels)): - (x, y, width, height), default_color = tiles[id(node)] - rgba = default_color if colors is None else colors[index % len(colors)] - leaf_style: dict[str, Any] = {"facecolor": rgba, **style} - patch = Rectangle((x, y), width, height, **leaf_style) - ax.add_patch(patch) - text = None - if label: - options = dict(text_style) - if isinstance(options["color"], str) and options["color"].lower() == "auto": - luminance = np.dot(patch.get_facecolor()[:3], [0.2126, 0.7152, 0.0722]) - options["color"] = "#18212b" if luminance > 0.5 else "white" - text = ax.text(x + width / 2, y + height / 2, label, **options) - text.set_clip_path(patch) - result["patches"].append(patch) - result["texts"].append(text) + tiles[id(node)] = _inset(box, pad), rgba, background + + # The axes frame is hidden for treemaps, exposing the figure background. + background = _composite(ax.figure.get_facecolor(), np.ones(3)) + with _draw_transaction(ax): + style = ax._parse_cycle(sum(node.value > 0 for node in nodes), **style) + layout(nodes, rect, background) + # Draw leaves in input order; only layout needs size sorting. + for index, (node, label) in enumerate(zip(leaves, labels)): + (x, y, width, height), default_color, background = tiles[id(node)] + rgba = default_color if colors is None else colors[index % len(colors)] + leaf_style: dict[str, Any] = {"facecolor": rgba, **style} + patch = Rectangle((x, y), width, height, **leaf_style) + ax.add_patch(patch) + text = None + if label: + options = dict(text_style) + if ( + isinstance(options["color"], str) + and options["color"].lower() == "auto" + ): + luminance = np.dot( + _composite(patch.get_facecolor(), background), + [0.2126, 0.7152, 0.0722], + ) + options["color"] = "#18212b" if luminance > 0.5 else "white" + text = ax.text(x + width / 2, y + height / 2, label, **options) + text.set_clip_path(patch) + result["patches"].append(patch) + result["texts"].append(text) ax.set_xlim(rect[0], rect[0] + rect[2]) ax.set_ylim(rect[1], rect[1] + rect[3]) ax.set_aspect("equal", adjustable="box") diff --git a/ultraplot/tests/test_treemap.py b/ultraplot/tests/test_treemap.py index a0116fe4d..3318c5c19 100644 --- a/ultraplot/tests/test_treemap.py +++ b/ultraplot/tests/test_treemap.py @@ -436,3 +436,54 @@ def test_treemap_extreme_size_range(): middle = result["patches"][1] assert middle.get_width() * middle.get_height() == pytest.approx(1e-200, abs=0) _assert_tiling(result["patches"], (0, 0, 1, 1)) + + +@pytest.mark.parametrize( + "color,group_kw,expected", + [ + ("none", {}, "#18212b"), + ((0, 0, 0, 0.05), {}, "#18212b"), + ("none", {"facecolor": "black", "alpha": 1}, "white"), + ], +) +def test_translucent_treemap_label_contrast(color, group_kw, expected): + fig, ax = uplt.subplot() + fig.set_facecolor("white") + result = ax.treemap({"Outer": {"Inner": {"a": 1}}}, color=color, group_kw=group_kw) + assert result["texts"][0].get_color() == expected + assert result["patches"][0].get_facecolor()[3] == to_rgba(color)[3] + + +def test_failed_treemap_can_retry_on_same_axes(): + _, axs = uplt.subplots(ncols=2) + for ax in axs: + ax.scatter([10], [20]) + ax = axs[0] + artists = ax.get_children() + bounds = ax.dataLim.frozen() + with uplt.rc.context({"text.align": True}), pytest.raises(ValueError): + ax.treemap( + {"group": {"a": 1}}, cycle=["r", "b"], text_kw={"color": "bad-color"} + ) + assert ax.get_children() == artists + assert ax.dataLim.bounds == bounds.bounds + np.testing.assert_equal(ax.dataLim.minpos, bounds.minpos) + assert not ax._align_texts + assert ( + ax.treemap([1])["patches"][0].get_facecolor() + == axs[1].treemap([1])["patches"][0].get_facecolor() + ) + + +def test_nested_totals_larger_than_float_range(): + _, ax = uplt.subplot() + result = ax.treemap( + {"Outer": {"Inner": {"a": 1e308, "b": 1e308}, "c": 1e308}, "d": 1e308}, + pad=0, + group_pad=0, + group_labels=False, + ) + assert result["values"] == [1e308] * 4 + assert [p.get_width() * p.get_height() for p in result["patches"]] == pytest.approx( + [0.25] * 4 + ) From 2e0e11309cf89dfde65df17b7d4bd6bbc96cda61 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 19 Nov 2026 10:16:28 +0100 Subject: [PATCH 09/11] Align treemap facecolor aliases and group label contrast --- ultraplot/axes/plot.py | 5 +++-- ultraplot/axes/plot_types/treemap.py | 32 +++++++++++++++++----------- ultraplot/internals/rcsetup.py | 5 +++++ ultraplot/tests/test_treemap.py | 30 ++++++++++++++++++++++++++ 4 files changed, 57 insertions(+), 15 deletions(-) diff --git a/ultraplot/axes/plot.py b/ultraplot/axes/plot.py index aa269ccba..c73a288ff 100644 --- a/ultraplot/axes/plot.py +++ b/ultraplot/axes/plot.py @@ -6839,7 +6839,8 @@ def treemap( cycle_kw : dict, optional Keyword arguments passed to `~ultraplot.constructor.Cycle`. cmap : colormap, optional - Color leaves by size. Mutually exclusive with ``color``. + Color leaves by size. Mutually exclusive with explicit leaf colors, + including ``facecolor`` and its aliases. norm : matplotlib.colors.Normalize, optional Normalization for ``cmap``. Cannot be combined with vmin/vmax. vmin, vmax : float, optional @@ -6862,7 +6863,7 @@ def treemap( clipped to its tile. Other keyword arguments style leaf rectangles. Explicit properties override the ``treemap.patch.*``, ``treemap.group.*``, and ``treemap.text.*`` rc defaults. Group label - size and weight follow ``treemap.group.text.*``. Omitted options + color, size, and weight follow ``treemap.group.text.*``. Omitted options are resolved from rc at call time; explicit False and zero win. Returns diff --git a/ultraplot/axes/plot_types/treemap.py b/ultraplot/axes/plot_types/treemap.py index 6ed84ec36..bc79a0da6 100644 --- a/ultraplot/axes/plot_types/treemap.py +++ b/ultraplot/axes/plot_types/treemap.py @@ -203,6 +203,14 @@ def _composite(foreground, background): return rgb * alpha + background * (1 - alpha) +def _label_style(style, background): + color = style["color"] + if isinstance(color, str) and color.lower() == "auto": + luminance = np.dot(background, [0.2126, 0.7152, 0.0722]) + return {**style, "color": "#18212b" if luminance > 0.5 else "white"} + return style + + @contextmanager def _draw_transaction(ax): """Restore artists, data bounds, and cycle positions if a style fails.""" @@ -260,7 +268,11 @@ def treemap( raise ValueError("treemap requires Cartesian axes with linear scales.") nodes = _nodes(sizes, labels) style = _style("patch", "patch", kwargs) - color = _not_none(color=color, colors=style.pop("color", None)) + color = _not_none( + color=color, + colors=style.pop("color", None), + facecolor=style.pop("facecolor", None), + ) if color is not None and cmap is not None: raise ValueError("Use either color or cmap, not both.") leaves = [leaf for node in nodes for leaf in node.leaves()] @@ -338,19 +350,20 @@ def layout( result["groups"].append(patch) inner = _inset(box, group_pad) header = min(0.05 * rect[3], inner[3] * 0.18) if group_labels else 0 + group_background = _composite(patch.get_facecolor(), background) if group_labels: label = ax.text( inner[0], inner[1] + inner[3] - header / 2, node.label, - **group_text_style, + **_label_style(group_text_style, group_background), ) label.set_clip_path(patch) result["group_texts"].append(label) layout( node.children, (*inner[:3], inner[3] - header), - _composite(patch.get_facecolor(), background), + group_background, hue, ) else: @@ -373,16 +386,9 @@ def layout( ax.add_patch(patch) text = None if label: - options = dict(text_style) - if ( - isinstance(options["color"], str) - and options["color"].lower() == "auto" - ): - luminance = np.dot( - _composite(patch.get_facecolor(), background), - [0.2126, 0.7152, 0.0722], - ) - options["color"] = "#18212b" if luminance > 0.5 else "white" + options = _label_style( + text_style, _composite(patch.get_facecolor(), background) + ) text = ax.text(x + width / 2, y + height / 2, label, **options) text.set_clip_path(patch) result["patches"].append(patch) diff --git a/ultraplot/internals/rcsetup.py b/ultraplot/internals/rcsetup.py index 24ffefff1..929785d18 100644 --- a/ultraplot/internals/rcsetup.py +++ b/ultraplot/internals/rcsetup.py @@ -2084,6 +2084,11 @@ def _validator_accepts(validator, value): functools.partial(_validate_color, alternative="auto"), "Treemap leaf label color; auto selects dark or white text for contrast.", ), + "treemap.group.text.color": ( + "auto", + functools.partial(_validate_color, alternative="auto"), + "Treemap group label color. Auto selects dark or white text for contrast.", + ), "treemap.group.text.size": ( 10.0, _validate_fontsize, diff --git a/ultraplot/tests/test_treemap.py b/ultraplot/tests/test_treemap.py index 3318c5c19..b54026721 100644 --- a/ultraplot/tests/test_treemap.py +++ b/ultraplot/tests/test_treemap.py @@ -487,3 +487,33 @@ def test_nested_totals_larger_than_float_range(): assert [p.get_width() * p.get_height() for p in result["patches"]] == pytest.approx( [0.25] * 4 ) + + +@pytest.mark.parametrize( + "alias", ["facecolor", "fc", "facecolors", "fillcolor", "fillcolors"] +) +def test_leaf_facecolor_aliases(alias): + _, ax = uplt.subplot() + with pytest.raises(ValueError, match="color or cmap"): + ax.treemap([1, 2], cmap="viridis", **{alias: "red"}) + result = ax.treemap([1, 3, 2], **{alias: ["r", "b"]}) + assert [p.get_facecolor() for p in result["patches"]] == [to_rgba(c) for c in "rbr"] + + +@pytest.mark.parametrize( + "fill,alpha,ink,expected", + [ + ("black", 1, "auto", "white"), + ("black", 0.05, "auto", "#18212b"), + ("white", 1, "auto", "#18212b"), + ("black", 1, "orange", "orange"), + ], +) +def test_group_heading_color(fill, alpha, ink, expected): + fig, ax = uplt.subplot() + fig.set_facecolor("white") + with uplt.rc.context({"treemap.group.text.color": ink}): + result = ax.treemap( + {"Outer": {"Inner": {"A": 1}}}, group_kw={"fc": fill, "alpha": alpha} + ) + assert [t.get_color() for t in result["group_texts"]] == [expected, expected] From 536827adfcd3321a674eeeee1485fa89662619b4 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 19 Nov 2026 10:18:31 +0100 Subject: [PATCH 10/11] Validate treemap rectangle endpoints before drawing --- ultraplot/internals/rcsetup.py | 6 +++++- ultraplot/tests/test_treemap.py | 2 ++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/ultraplot/internals/rcsetup.py b/ultraplot/internals/rcsetup.py index 929785d18..d40b7cfee 100644 --- a/ultraplot/internals/rcsetup.py +++ b/ultraplot/internals/rcsetup.py @@ -535,7 +535,11 @@ def _validate_treemap_rect(value: Any) -> tuple[float, float, float, float]: raise ValueError( "treemap.rect must be (x, y, width, height) with positive dimensions." ) - return float(array[0]), float(array[1]), float(array[2]), float(array[3]) + x, y, width, height = map(float, array) + right, top = x + width, y + height + if not (x < right < float("inf") and y < top < float("inf")): + raise ValueError("treemap.rect endpoints must be finite and distinct.") + return x, y, width, height def _validate_treemap_format(value: Any) -> str | Callable[[float], str]: diff --git a/ultraplot/tests/test_treemap.py b/ultraplot/tests/test_treemap.py index b54026721..49bd6bce0 100644 --- a/ultraplot/tests/test_treemap.py +++ b/ultraplot/tests/test_treemap.py @@ -211,6 +211,8 @@ def test_treemap_named_cycle_and_cycle_options(): ([1, 2], {"labels": ["A"]}), ([1], {"pad": -1}), ([1], {"rect": (0, 0, 0, 1)}), + ([1], {"rect": (1e308, 0, 1e308, 1)}), + ([1], {"rect": (0, 1e20, 1, 1)}), ([1], {"color": "red", "cmap": "viridis"}), ([1, 2], {"color": []}), ([1], {"colors": ["r"], "vmin": 0}), From 591e61ffccd7945002367ad01c1d2fd184c4545a Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 19 Nov 2026 10:24:01 +0100 Subject: [PATCH 11/11] Preserve cycle options and transparent treemap fills --- ultraplot/axes/plot.py | 2 +- ultraplot/axes/plot_types/treemap.py | 11 +++++++++-- ultraplot/tests/test_treemap.py | 9 +++++++++ 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/ultraplot/axes/plot.py b/ultraplot/axes/plot.py index c73a288ff..e1e4ce9bf 100644 --- a/ultraplot/axes/plot.py +++ b/ultraplot/axes/plot.py @@ -4473,7 +4473,7 @@ def _parse_cycle( Whether to simply return the property cycle or apply it. The cycle is only applied (and therefore reset) if it differs from the current one. """ - cycle_kw = cycle_kw or {} + cycle_kw = dict(cycle_kw or {}) # Ignore singular column plotting if ncycle != 1: cycle_kw.setdefault("N", ncycle) diff --git a/ultraplot/axes/plot_types/treemap.py b/ultraplot/axes/plot_types/treemap.py index bc79a0da6..f95cd5fc8 100644 --- a/ultraplot/axes/plot_types/treemap.py +++ b/ultraplot/axes/plot_types/treemap.py @@ -278,7 +278,7 @@ def treemap( leaves = [leaf for node in nodes for leaf in node.leaves()] values = np.array([node.value for node in leaves]) mappable: mcm.ScalarMappable | None = None - colors: NDArray[np.float64] | None = None + colors: Sequence[Any] | NDArray[np.float64] | None = None if cmap is None and any(option is not None for option in (norm, vmin, vmax)): raise ValueError("norm, vmin, and vmax require cmap.") if cmap is not None: @@ -291,7 +291,14 @@ def treemap( mappable.autoscale_None() colors = mappable.to_rgba(values) elif color is not None: - colors = mcolors.to_rgba_array([color] if isinstance(color, str) else color) + palette = [color] if isinstance(color, str) else color + colors = mcolors.to_rgba_array(palette) + # Matplotlib keeps "none" transparent even when the patch sets alpha. + # An RGBA tuple with alpha zero intentionally behaves differently. + if len(colors) == len(palette) and any( + isinstance(c, str) and c.lower() == "none" for c in palette + ): + colors = palette if len(colors) == 0: raise ValueError("color must contain at least one color.") parent_style = _style("group", "patch", group_kw) diff --git a/ultraplot/tests/test_treemap.py b/ultraplot/tests/test_treemap.py index 49bd6bce0..82ed1291c 100644 --- a/ultraplot/tests/test_treemap.py +++ b/ultraplot/tests/test_treemap.py @@ -191,6 +191,7 @@ def test_treemap_named_cycle_and_cycle_options(): _, ax = uplt.subplots() options = {"reverse": True} result = ax.treemap([1, 0, 3, 2], cycle="colorblind", cycle_kw=options) + assert options == {"reverse": True} expected = uplt.Cycle("colorblind", N=3, reverse=True).by_key()["color"] np.testing.assert_allclose( [p.get_facecolor() for p in result["patches"]], @@ -519,3 +520,11 @@ def test_group_heading_color(fill, alpha, ink, expected): {"Outer": {"Inner": {"A": 1}}}, group_kw={"fc": fill, "alpha": alpha} ) assert [t.get_color() for t in result["group_texts"]] == [expected, expected] + + +@pytest.mark.parametrize("palette", ["none", ["none", (1, 0, 0, 0)]]) +def test_none_fill_stays_transparent_with_patch_alpha(palette): + _, ax = uplt.subplot() + result = ax.treemap([1, 2, 3], colors=palette, alpha=0.5) + expected = [0, 0, 0] if isinstance(palette, str) else [0, 0.5, 0] + assert [patch.get_facecolor()[3] for patch in result["patches"]] == expected