diff --git a/src/maxplotlib/tests/test_web.py b/src/maxplotlib/tests/test_web.py index ba38fd8..92f1532 100644 --- a/src/maxplotlib/tests/test_web.py +++ b/src/maxplotlib/tests/test_web.py @@ -207,3 +207,25 @@ def test_a_figure_without_caption_has_none(): canvas.plot(np.arange(3), np.arange(3)) figure, _ = canvas.plot_matplotlib() assert getattr(figure, "caption", None) is None + + +def test_the_arrays_of_a_web_figure_are_single_precision(): + import base64 + + x = np.linspace(0.0, 1.0, 50) + fig = go.Figure( + go.Heatmap(z=np.outer(x, x)), + frames=[go.Frame(data=[go.Heatmap(z=np.outer(x, x) * 2)])], + ) + web = web_figure(fig) + z = web["data"][0]["z"] + assert z["dtype"] == "f4" + values = np.frombuffer(base64.b64decode(z["bdata"]), dtype=" str | None: return title if isinstance(title, str) and title else None +def _single_precision(value: Any) -> Any: + """``value`` with its double-precision arrays in single precision. + + Plotly writes NumPy arrays as typed arrays, ``{"dtype": "f8", "bdata": ...}``; a figure on a + page needs no more than the seven digits of single precision, and its file is half as large. + """ + if isinstance(value, dict): + if value.get("dtype") == "f8" and isinstance(value.get("bdata"), str): + import numpy as np + + data = np.frombuffer(base64.b64decode(value["bdata"]), dtype=" dict: slot = _trace_slot(trace) if slot is None: @@ -207,7 +231,9 @@ def web_figure( Returns ------- dict - ``data``, ``layout`` and ``frames`` (when the figure has frames) of the web figure. + ``data``, ``layout`` and ``frames`` (when the figure has frames) of the web figure. The + arrays of the traces are in single precision: seven digits are plenty on a page, and + the file is half as large. Examples -------- @@ -251,13 +277,21 @@ def web_figure( layout["meta"] = meta web = { - "data": [_with_slot(trace) for trace in source.get("data") or []], + "data": [ + _single_precision(_with_slot(trace)) for trace in source.get("data") or [] + ], "layout": layout, } frames = source.get("frames") if frames: web["frames"] = [ - {**frame, "data": [_with_slot(trace) for trace in frame.get("data") or []]} + { + **frame, + "data": [ + _single_precision(_with_slot(trace)) + for trace in frame.get("data") or [] + ], + } for frame in frames ] return web