diff --git a/docs/examples/plot_types/14_treemap.py b/docs/examples/plot_types/14_treemap.py new file mode 100644 index 000000000..7bef3329e --- /dev/null +++ b/docs/examples/plot_types/14_treemap.py @@ -0,0 +1,28 @@ +""" +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 + +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].format(title="Flat categories") +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 c3ea7a509..e1e4ce9bf 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. @@ -4453,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) @@ -6769,6 +6789,124 @@ def violinploth(self, *args, **kwargs): kwargs = _parse_vert(default_vert=False, **kwargs) return self._apply_violinplot(*args, **kwargs) + def treemap( + self, + sizes: "TreemapInput", + labels: Sequence[Any] | str | None = None, + *, + 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. + + 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 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. 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 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 + 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 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 + Colormap bounds when ``norm`` is omitted. + 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: :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: :rc:`treemap.group_labels` + Reserve a header for each group name. + show_values : bool, default: :rc:`treemap.show_values` + Add the numeric size below each leaf label. + 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 + color, size, and weight follow ``treemap.group.text.*``. Omitted options + are resolved from rc at call time; explicit False and zero win. + + Returns + ------- + 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`` + 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}) + >>> data = {'amount': [2, 3, 4], 'name': ['A', 'B', 'C']} + >>> 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, _ = inputs._from_data(data, sizes, None) + 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..f95cd5fc8 --- /dev/null +++ b/ultraplot/axes/plot_types/treemap.py @@ -0,0 +1,407 @@ +"""Area-proportional, squarified treemaps using native Matplotlib artists.""" + +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 + +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 _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 + + 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 | Fraction + 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, + labels: Sequence[Any] | None = None, + path: NodePath = (), +) -> list[_Node]: + """Validate the complete hierarchy before adding any artists.""" + if isinstance(sizes, Mapping) or ( + labels is None and getattr(sizes, "ndim", None) == 1 and hasattr(sizes, "items") + ): + if labels is not None: + 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(): + child_path = (*path, key) + if isinstance(value, Mapping): + children = _nodes(cast(TreemapHierarchy, value), path=child_path) + 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( + _Node(str(key), _validate_nonnegative_float(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): + 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,)) + 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 _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) + scale = max(node.value 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) + for i in reversed(range(len(weights))): + remaining[i] = remaining[i + 1] + weights[i] + + result: list[tuple[_Node, Bounds]] = [] + start = 0 + while start < len(ordered): + vertical = 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 i in range(start, end): + length = short * (weights[i] / weight) + box = (x, offset, strip, length) if vertical else (offset, y, length, strip) + result.append((ordered[i], box)) + offset += length + if vertical: + x += strip + width = long * (remaining[end] / total) + else: + y += strip + height = long * (remaining[end] / total) + start = end + return result + + +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 _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 _composite(foreground, background): + rgb = np.asarray(foreground[:3]) + alpha = foreground[3] + 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.""" + 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, + labels: Sequence[Any] | 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: + """Resolve rc defaults and draw :meth:`PlotAxes.treemap`.""" + 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 = _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) + style = _style("patch", "patch", kwargs) + 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()] + values = np.array([node.value for node in leaves]) + mappable: mcm.ScalarMappable | 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: + 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 = mappable.to_rgba(values) + elif color is not None: + 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) + 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. + labels = [node.label for node in leaves] + if show_values: + 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": [node.path for node in leaves], + "values": values.tolist(), + "mappable": mappable, + } + tiles: dict[int, tuple[Bounds, NDArray[np.float64], NDArray[np.float64]]] = {} + + def layout( + 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)} + 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 + 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) + 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, + **_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), + group_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, 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 = _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) + 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") + ax.set_axis_off() + return result diff --git a/ultraplot/internals/rcsetup.py b/ultraplot/internals/rcsetup.py index 27737fbce..d40b7cfee 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,43 @@ 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." + ) + 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]: + """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 +2030,79 @@ 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.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, + "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 new file mode 100644 index 000000000..82ed1291c --- /dev/null +++ b/ultraplot/tests/test_treemap.py @@ -0,0 +1,530 @@ +"""Treemap area conservation, hierarchy, and public plotting behavior.""" + +from pathlib import Path + +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() + 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() + 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() + 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() + + +@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 = container({"amount": [1, 3], "names": ["A", "B"]}) + other = axs[1].treemap( + "amount", + labels=lookup["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("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): + _, 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) + 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"]], + [to_rgba(color) for color in expected], + ) + + +@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], {"rect": (1e308, 0, 1e308, 1)}), + ([1], {"rect": (0, 1e20, 1, 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"}), + ], +) +def test_treemap_invalid_data_does_not_add_artists(sizes, kwargs): + fig, ax = uplt.subplots() + before = (list(ax.patches), list(ax.texts)) + 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(): + data = {"Group": {"Alpha": 3, "Beta": 2}, "Other": 1} + text_kw = {"fontsize": 8} + group_kw = {"lw": 2} + fig, ax = uplt.subplots() + 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( + "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] + 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: + 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] + 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: + 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() + 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: + 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] + 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) + 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( + "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} + 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() + + +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)) + + +@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 + ) + + +@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] + + +@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