|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from copy import deepcopy |
| 4 | +from typing import TYPE_CHECKING |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +from PIL.Image import Image as PILImage |
| 8 | + |
| 9 | +from ..themes.theme import theme |
| 10 | + |
| 11 | +if TYPE_CHECKING: |
| 12 | + from matplotlib.figure import Figure |
| 13 | + from matplotlib.patches import Rectangle |
| 14 | + from matplotlib.transforms import Bbox |
| 15 | + |
| 16 | + from plotnine._mpl.figure import p9Figure |
| 17 | + |
| 18 | + from ..ggplot import ggplot |
| 19 | + from ..themes.theme import theme as theme_type |
| 20 | + |
| 21 | + |
| 22 | +class _InsetImage: |
| 23 | + """ |
| 24 | + A raster image rendered inside an `inset_element`'s bounding box |
| 25 | +
|
| 26 | + The image keeps its intrinsic aspect ratio — when the bbox does |
| 27 | + not match, the image is letterboxed with transparent padding on |
| 28 | + the two opposing edges so it stays centred. |
| 29 | +
|
| 30 | + Theming the inset (`inset_element(...) + theme(...)`) draws a |
| 31 | + background rectangle around the image; only `plot_background` |
| 32 | + is honored, and it styles that rectangle's fill and border. |
| 33 | + """ |
| 34 | + |
| 35 | + # The host figure this inset renders into. |
| 36 | + figure: p9Figure |
| 37 | + # Theme that styles the background rectangle. |
| 38 | + theme: theme_type |
| 39 | + # Background rectangle drawn around the image. |
| 40 | + patch: Rectangle |
| 41 | + |
| 42 | + # Bbox that defines the position and size of the final image |
| 43 | + # artist. When the original image is mapped onto the figure, |
| 44 | + # this bbox sets where on the figure it lands and how big it is. |
| 45 | + _frac_bbox: Bbox |
| 46 | + |
| 47 | + def __init__(self, image: PILImage | np.ndarray): |
| 48 | + from matplotlib.transforms import Bbox |
| 49 | + |
| 50 | + self._image = image |
| 51 | + self._image_size = _image_size(image) # (W, H) px |
| 52 | + self._frac_bbox = Bbox.unit() |
| 53 | + self.theme = theme() |
| 54 | + |
| 55 | + def __add__(self, other: object) -> _InsetImage: |
| 56 | + if not isinstance(other, theme): |
| 57 | + return NotImplemented |
| 58 | + |
| 59 | + new = deepcopy(self) |
| 60 | + new.theme = (new.theme or theme()) + other |
| 61 | + return new |
| 62 | + |
| 63 | + def _setup(self, parent: ggplot): |
| 64 | + self.figure = parent.figure |
| 65 | + |
| 66 | + def _arrange_in_box( |
| 67 | + self, left: float, bottom: float, right: float, top: float |
| 68 | + ): |
| 69 | + """ |
| 70 | + Place the image inside the given box, preserving aspect ratio |
| 71 | +
|
| 72 | + The image is letterboxed — centered inside the box with |
| 73 | + transparent padding on the two opposing edges — so its |
| 74 | + intrinsic aspect ratio survives. The background rectangle |
| 75 | + tracks the same fitted box. |
| 76 | +
|
| 77 | + Parameters |
| 78 | + ---------- |
| 79 | + left, bottom, right, top : |
| 80 | + Fractional figure-coordinates of the box assigned to this |
| 81 | + inset by `inset_element.align_to`. |
| 82 | + """ |
| 83 | + l, b, r, t = _fit_aspect( |
| 84 | + left, bottom, right, top, self._image_size, self.figure |
| 85 | + ) |
| 86 | + w, h = r - l, t - b |
| 87 | + self._frac_bbox.bounds = (l, b, w, h) # pyright: ignore[reportAttributeAccessIssue] |
| 88 | + self.patch.set_bounds(l, b, w, h) |
| 89 | + |
| 90 | + def draw(self): |
| 91 | + from matplotlib.image import BboxImage |
| 92 | + from matplotlib.transforms import TransformedBbox |
| 93 | + |
| 94 | + image_artist = BboxImage( |
| 95 | + TransformedBbox(self._frac_bbox, self.figure.transFigure) |
| 96 | + ) |
| 97 | + image_artist.set_data(np.asarray(self._image)) |
| 98 | + self.figure.add_artist(image_artist) |
| 99 | + |
| 100 | + self.theme._setup(self) # pyright: ignore[reportArgumentType] |
| 101 | + self._draw_plot_background() |
| 102 | + self.theme.apply() |
| 103 | + |
| 104 | + def _draw_plot_background(self): |
| 105 | + from matplotlib.patches import Rectangle |
| 106 | + |
| 107 | + self.patch = self.figure.add_artist( |
| 108 | + Rectangle( |
| 109 | + (0, 0), |
| 110 | + 1, |
| 111 | + 1, |
| 112 | + facecolor="none", |
| 113 | + transform=self.figure.transFigure, |
| 114 | + ) |
| 115 | + ) |
| 116 | + self.theme.targets.plot_background = self.patch |
| 117 | + |
| 118 | + |
| 119 | +def _image_size(obj: PILImage | np.ndarray) -> tuple[int, int]: |
| 120 | + """ |
| 121 | + Return the (width, height) of a PIL image or ndarray in pixels |
| 122 | + """ |
| 123 | + if isinstance(obj, PILImage): |
| 124 | + return obj.size # PIL exposes (W, H) |
| 125 | + |
| 126 | + arr = np.asarray(obj) |
| 127 | + h, w = arr.shape[:2] # ndarray is HWC or HW |
| 128 | + return w, h |
| 129 | + |
| 130 | + |
| 131 | +def _fit_aspect( |
| 132 | + left: float, |
| 133 | + bottom: float, |
| 134 | + right: float, |
| 135 | + top: float, |
| 136 | + image_size: tuple[int, int], |
| 137 | + fig: Figure, |
| 138 | +) -> tuple[float, float, float, float]: |
| 139 | + """ |
| 140 | + Shrink the user's bbox to the largest centered sub-bbox with the |
| 141 | + image's intrinsic aspect ratio |
| 142 | + """ |
| 143 | + # figure size in px |
| 144 | + W, H = fig.bbox.size |
| 145 | + |
| 146 | + # box size in px |
| 147 | + box_w = (right - left) * W |
| 148 | + box_h = (top - bottom) * H |
| 149 | + |
| 150 | + img_w, img_h = image_size |
| 151 | + img_aspect = img_w / img_h |
| 152 | + box_aspect = box_w / box_h |
| 153 | + |
| 154 | + if img_aspect > box_aspect: |
| 155 | + # Wider than the box: fit width, letterbox vertically |
| 156 | + new_box_h = box_w / img_aspect |
| 157 | + pad_frac = (box_h - new_box_h) / 2 / H |
| 158 | + return left, bottom + pad_frac, right, top - pad_frac |
| 159 | + |
| 160 | + # Taller (or equal): fit height, letterbox horizontally |
| 161 | + new_box_w = box_h * img_aspect |
| 162 | + pad_frac = (box_w - new_box_w) / 2 / W |
| 163 | + return left + pad_frac, bottom, right - pad_frac, top |
0 commit comments