Determine x and y labels for showing RGB images. Attempts to infer which dimension is RGB/RGBA by size and order of dims.
(
darray: DataArray | Dataset,
x: Hashable | None,
y: Hashable | None,
rgb: Hashable | None,
)
| 329 | |
| 330 | |
| 331 | def _infer_xy_labels_3d( |
| 332 | darray: DataArray | Dataset, |
| 333 | x: Hashable | None, |
| 334 | y: Hashable | None, |
| 335 | rgb: Hashable | None, |
| 336 | ) -> tuple[Hashable, Hashable]: |
| 337 | """ |
| 338 | Determine x and y labels for showing RGB images. |
| 339 | |
| 340 | Attempts to infer which dimension is RGB/RGBA by size and order of dims. |
| 341 | |
| 342 | """ |
| 343 | assert rgb is None or rgb != x |
| 344 | assert rgb is None or rgb != y |
| 345 | # Start by detecting and reporting invalid combinations of arguments |
| 346 | assert darray.ndim == 3 |
| 347 | not_none = [a for a in (x, y, rgb) if a is not None] |
| 348 | if len(set(not_none)) < len(not_none): |
| 349 | raise ValueError( |
| 350 | "Dimension names must be None or unique strings, but imshow was " |
| 351 | f"passed x={x!r}, y={y!r}, and rgb={rgb!r}." |
| 352 | ) |
| 353 | for label in not_none: |
| 354 | if label not in darray.dims: |
| 355 | raise ValueError(f"{label!r} is not a dimension") |
| 356 | |
| 357 | # Then calculate rgb dimension if certain and check validity |
| 358 | could_be_color = [ |
| 359 | label |
| 360 | for label in darray.dims |
| 361 | if darray[label].size in (3, 4) and label not in (x, y) |
| 362 | ] |
| 363 | if rgb is None and not could_be_color: |
| 364 | raise ValueError( |
| 365 | "A 3-dimensional array was passed to imshow(), but there is no " |
| 366 | "dimension that could be color. At least one dimension must be " |
| 367 | "of size 3 (RGB) or 4 (RGBA), and not given as x or y." |
| 368 | ) |
| 369 | if rgb is None and len(could_be_color) == 1: |
| 370 | rgb = could_be_color[0] |
| 371 | if rgb is not None and darray[rgb].size not in (3, 4): |
| 372 | raise ValueError( |
| 373 | f"Cannot interpret dim {rgb!r} of size {darray[rgb].size} as RGB or RGBA." |
| 374 | ) |
| 375 | |
| 376 | # If rgb dimension is still unknown, there must be two or three dimensions |
| 377 | # in could_be_color. We therefore warn, and use a heuristic to break ties. |
| 378 | if rgb is None: |
| 379 | assert len(could_be_color) in (2, 3) |
| 380 | rgb = could_be_color[-1] |
| 381 | warnings.warn( |
| 382 | "Several dimensions of this array could be colors. Xarray " |
| 383 | f"will use the last possible dimension ({rgb!r}) to match " |
| 384 | "matplotlib.pyplot.imshow. You can pass names of x, y, " |
| 385 | "and/or rgb dimensions to override this guess.", |
| 386 | stacklevel=2, |
| 387 | ) |
| 388 | assert rgb is not None |
no test coverage detected
searching dependent graphs…