Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Add array SVG image and table to _repr_html_ #9301

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion xarray/core/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -637,7 +637,7 @@ def short_array_repr(array):
def short_data_repr(array):
"""Format "data" for DataArray and Variable."""
internal_data = getattr(array, "variable", array)._data
if isinstance(array, np.ndarray):
if isinstance(internal_data, np.ndarray):
return short_array_repr(array)
elif is_duck_array(internal_data):
return limit_lines(repr(array.data), limit=40)
Expand Down
34 changes: 32 additions & 2 deletions xarray/core/formatting_html.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import math
import uuid
from collections import OrderedDict
from collections.abc import Mapping
Expand All @@ -14,6 +15,9 @@
short_data_repr,
)
from xarray.core.options import _get_boolean_with_default
from xarray.vendor.dask.array.svg import svg
from xarray.vendor.dask.utils import format_bytes
from xarray.vendor.dask.widgets.widgets import get_template

STATIC_FILES = (
("xarray.static.html", "icons-svg-inline.html"),
Expand All @@ -33,13 +37,39 @@ def _load_static_files():
]


def data_repr_template(array):
name = getattr(array, "name", "")
array_grid = svg(tuple((s,) for s in array.shape), dims=array.dims, name=name)
if not math.isnan(array.nbytes):
nbytes = format_bytes(array.nbytes)
else:
nbytes = "unknown"

array_svg_repr = get_template("array.html.j2").render(
array=array,
nbytes=nbytes,
grid=array_grid,
)
array_text_repr = collapsible_section(
name="Values",
details=escape(short_data_repr(array)),
n_items=25,
enabled=True,
collapsed=True,
)
return f"<pre>{array_text_repr}</pre>{array_svg_repr}"


def short_data_repr_html(array) -> str:
"""Format "data" for DataArray and Variable."""
internal_data = getattr(array, "variable", array)._data
if hasattr(internal_data, "_repr_html_"):
return internal_data._repr_html_()
text = escape(short_data_repr(array))
return f"<pre>{text}</pre>"
else:
try:
return data_repr_template(array)
except:
return f"<pre>{escape(short_data_repr(array))}</pre>"


def format_dims(dim_sizes, dims_with_index) -> str:
Expand Down
Loading
Loading