Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

`Arviz` plotting library fix (#2311)

Srihari Thyagarajan20990d3dbebc
diff --git a/marimo/_output/formatters/arviz_formatters.py b/marimo/_output/formatters/arviz_formatters.py
new file mode 100644
index 0000000000..f5fa56d9cb
--- /dev/null
+++ b/marimo/_output/formatters/arviz_formatters.py
@@ -0,0 +1,165 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from marimo._messaging.mimetypes import KnownMimeType
+from marimo._output.formatters.formatter_factory import FormatterFactory
+
+if TYPE_CHECKING:
+ import matplotlib.pyplot as plt # type: ignore
+ import numpy as np # type: ignore
+ from matplotlib.figure import Figure # type: ignore
+
+
+class ArviZFormatter(FormatterFactory):
+ @staticmethod
+ def package_name() -> str:
+ return "arviz"
+
+ def register(self) -> None:
+ import arviz as az # type: ignore
+ import matplotlib.pyplot as plt # type: ignore
+ import numpy as np # type: ignore
+
+ from marimo._output import formatting
+
+ @formatting.formatter(az.InferenceData) # type: ignore
+ def _format_inference_data(
+ data: az.InferenceData, # type: ignore
+ ) -> tuple[KnownMimeType, str]:
+ return ("text/plain", str(data))
+
+ @formatting.formatter(np.ndarray) # type: ignore
+ def _format_ndarray(
+ arr: np.ndarray, # type: ignore
+ ) -> tuple[KnownMimeType, str]:
+ return self.format_numpy_axes(arr)
+
+ @formatting.formatter(dict) # type: ignore
+ def _format_dict(
+ d: dict, # type: ignore
+ ) -> tuple[KnownMimeType, str]:
+ return self.format_dict_with_plot(d)
+
+ @formatting.formatter(plt.Figure) # type: ignore
+ def _format_figure(
+ fig: plt.Figure, # type: ignore
+ ) -> tuple[KnownMimeType, str]:
+ return self.format_figure(fig)
+
+ @formatting.formatter(object)
+ def _format_arviz_plot(
+ obj: Any,
+ ) -> tuple[KnownMimeType, str]:
+ return self.format_arviz_plot(obj)
+
+ @classmethod
+ def format_numpy_axes(cls, arr: np.ndarray) -> tuple[KnownMimeType, str]: # type: ignore
+ import matplotlib.pyplot as plt # type: ignore
+
+ # Check if array contains axes (to render plots) or not
+ if arr.dtype == object and cls._contains_axes(arr):
+ fig = plt.gcf()
+ if fig.get_axes(): # Only process if there are axes to show
+ axes_info = cls._get_axes_info(fig)
+ plot_html = cls._get_plot_html(fig)
+ plt.close(fig) # Safely close the figure after saving
+ combined_html = f"<pre>{axes_info}</pre><br>{plot_html}"
+ return ("text/html", combined_html)
+ # Fallback to plain text if no axes or plot are present
+ return ("text/plain", str(arr))
+
+ @staticmethod
+ def _contains_axes(arr: np.ndarray) -> bool: # type: ignore
+ from matplotlib.axes import Axes # type: ignore
+
+ """
+ Check if the numpy array contains any matplotlib Axes objects.
+ To ensure performance for large arrays, we limit the check to the
+ first 100 items. This should be sufficient for most use cases
+ while avoiding excessive computation time.
+ """
+ # Cap the number of items to check for performance reasons
+ MAX_ITEMS_TO_CHECK = 100
+
+ if arr.ndim == 1:
+ # For 1D arrays, check up to MAX_ITEMS_TO_CHECK items
+ return any(
+ isinstance(item, Axes) for item in arr[:MAX_ITEMS_TO_CHECK]
+ )
+ elif arr.ndim == 2:
+ # For 2D arrays, check up to MAX_ITEMS_TO_CHECK items in total
+ items_checked = 0
+ for row in arr:
+ for item in row:
+ if isinstance(item, Axes):
+ return True
+ items_checked += 1
+ if items_checked >= MAX_ITEMS_TO_CHECK:
+ return False
+ return False
+
+ @staticmethod
+ def _get_axes_info(fig: Figure) -> str: # type: ignore
+ axes_info = []
+ for _, ax in enumerate(fig.axes):
+ bbox = ax.get_position()
+ axes_info.append(
+ f"Axes({bbox.x0:.3f},{bbox.y0:.3f};"
+ f"{bbox.width:.3f}x{bbox.height:.3f})"
+ )
+ return "\n".join(axes_info)
+
+ @staticmethod
+ def _get_plot_html(fig: Figure) -> str: # type: ignore
+ import base64
+ from io import BytesIO
+
+ buf = BytesIO()
+ fig.savefig(buf, format="png", bbox_inches="tight") # Retain default
+ data = base64.b64encode(buf.getbuffer()).decode("ascii")
+ return f"<img src='data:image/png;base64,{data}'/>"
+
+ @classmethod
+ def format_dict_with_plot(cls, d: dict) -> tuple[KnownMimeType, str]: # type: ignore
+ import matplotlib.pyplot as plt # type: ignore
+
+ str_repr = str(d)
+ fig = plt.gcf()
+ if fig.get_axes():
+ axes_info = cls._get_axes_info(fig)
+ plot_html = cls._get_plot_html(fig)
+ plt.close(fig)
+ combined_html = (
+ f"<pre>{str_repr}\n{axes_info}</pre><br>" f"{plot_html}"
+ )
+ return ("text/html", combined_html)
+ return ("text/plain", str_repr)
+
+ @classmethod
+ def format_figure(cls, fig: Figure) -> tuple[KnownMimeType, str]: # type: ignore
+ import matplotlib.pyplot as plt # type: ignore
+
+ axes_info = cls._get_axes_info(fig)
+ plot_html = cls._get_plot_html(fig)
+ plt.close(fig)
+ combined_html = f"<pre>{axes_info}</pre><br>{plot_html}"
+ return ("text/html", combined_html)
+
+ @classmethod
+ def format_arviz_plot(cls, result: Any) -> tuple[KnownMimeType, str]:
+ import matplotlib.pyplot as plt # type: ignore
+ import numpy as np # type: ignore
+ from matplotlib.figure import Figure # type: ignore
+
+ if isinstance(result, Figure):
+ return cls.format_figure(result)
+ elif isinstance(result, np.ndarray):
+ return cls.format_numpy_axes(result)
+ elif isinstance(result, dict):
+ return cls.format_dict_with_plot(result)
+ else:
+ fig = plt.gcf()
+ if fig.get_axes():
+ return cls.format_figure(fig)
+ return ("text/plain", str(result))
diff --git a/marimo/_output/formatters/formatters.py b/marimo/_output/formatters/formatters.py
index b93018918b..2aa7aaf92f 100644
--- a/marimo/_output/formatters/formatters.py
+++ b/marimo/_output/formatters/formatters.py
@@ -7,6 +7,7 @@ from typing import Any, Callable, Sequence
from marimo._config.config import Theme
from marimo._output.formatters.altair_formatters import AltairFormatter
from marimo._output.formatters.anywidget_formatters import AnyWidgetFormatter
+from marimo._output.formatters.arviz_formatters import ArviZFormatter
from marimo._output.formatters.bokeh_formatters import BokehFormatter
from marimo._output.formatters.cell import CellFormatter
from marimo._output.formatters.df_formatters import (
@@ -44,6 +45,7 @@ THIRD_PARTY_FACTORIES: dict[str, FormatterFactory] = {
IPythonFormatter.package_name(): IPythonFormatter(),
IPyWidgetsFormatter.package_name(): IPyWidgetsFormatter(),
AnyWidgetFormatter.package_name(): AnyWidgetFormatter(),
+ ArviZFormatter.package_name(): ArviZFormatter(),
TqdmFormatter.package_name(): TqdmFormatter(),
LetsPlotFormatter.package_name(): LetsPlotFormatter(),
SympyFormatter.package_name(): SympyFormatter(),
diff --git a/marimo/_smoke_tests/bugs/1033.py b/marimo/_smoke_tests/bugs/1033.py
new file mode 100644
index 0000000000..5a14385cf6
--- /dev/null
+++ b/marimo/_smoke_tests/bugs/1033.py
@@ -0,0 +1,334 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "arviz",
+# "marimo",
+# "xarray",
+# "matplotlib",
+# "scipy",
+# "numpy",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.8.15"
+app = marimo.App(width="medium")
+
+
+def __(az):
+ _data = az.load_arviz_data('centered_eight')
+ az.plot_autocorr(_data)
+ # [az.plot_autocorr(_data),
+ # type(az.plot_autocorr(_data))]
+ return
+
+
+def __(az, np):
+ _idata = az.from_dict(posterior={"a":np.random.normal(1, 0.5, 5000)},
+ prior={"a":np.random.normal(0, 1, 5000)})
+ az.plot_bf(_idata, var_name="a", ref_val=0)
+ # [az.plot_bf(_idata, var_name="a", ref_val=0),
+ # type(az.plot_bf(_idata, var_name="a", ref_val=0))]
+ return
+
+
+def __(az, np):
+ _data = az.load_arviz_data("regression1d")
+ # [az.plot_bpv(_data, kind="t_stat", t_stat=lambda x:np.percentile(x, q=50, axis=-1)), type(az.plot_bpv(_data, kind="t_stat", t_stat=lambda x:np.percentile(x, q=50, axis=-1)))]
+ az.plot_bpv(_data, kind="t_stat", t_stat=lambda x:np.percentile(x, q=50, axis=-1))
+ return
+
+
+def __(az):
+ _model_compare = az.compare({'Centered 8 schools': az.load_arviz_data('centered_eight'),
+ 'Non-centered 8 schools': az.load_arviz_data('non_centered_eight')})
+ # [az.plot_compare(_model_compare), type(az.plot_compare(_model_compare))]
+ az.plot_compare(_model_compare)
+ return
+
+
+def __(az):
+ _centered = az.load_arviz_data('centered_eight')
+ _non_centered = az.load_arviz_data('non_centered_eight')
+ # [az.plot_density([_centered, _non_centered]), type(az.plot_density([_centered, _non_centered]))]
+ az.plot_density([_centered, _non_centered])
+ return
+
+
+def __():
+ # az.clear_data_home()
+ # _data = az.load_arviz_data('rugby')
+ # [az.plot_dist_comparison(_data, var_names=["defs"], coords={"team" : ["Italy"]}), type(az.plot_dist_comparison(_data, var_names=["defs"], coords={"team" : ["Italy"]}))]
+ return
+
+
+def __(az, np):
+ _values = np.random.normal(0, 1, 500)
+ # [az.plot_dot(_values), type(az.plot_dot(_values))]
+ az.plot_dot(_values)
+ return
+
+
+def __(az, norm, np):
+ _sample = norm(0,1).rvs(1000)
+ _npoints = 100
+ # [az.plot_ecdf(_sample, eval_points=np.linspace(_sample.min(), _sample.max(), _npoints)), type(az.plot_ecdf(_sample, eval_points=np.linspace(_sample.min(), _sample.max(), _npoints)))]
+ az.plot_ecdf(_sample, eval_points=np.linspace(_sample.min(), _sample.max(), _npoints))
+ return
+
+
+def __(az):
+ _idata1 = az.load_arviz_data("centered_eight")
+ _idata2 = az.load_arviz_data("non_centered_eight")
+ # [az.plot_elpd(
+ # {"centered model": _idata1, "non centered model": _idata2},
+ # xlabels=True
+ # ), type(az.plot_elpd(
+ # {"centered model": _idata1, "non centered model": _idata2},
+ # xlabels=True
+ # ))]
+ az.plot_elpd(
+ {"centered model": _idata1, "non centered model": _idata2},
+ xlabels=True
+ )
+ return
+
+
+def __(az):
+ _data = az.load_arviz_data('centered_eight')
+ # [az.plot_energy(_data), type(az.plot_energy(_data))]
+ az.plot_energy(_data)
+ return
+
+
+def __(az):
+ _idata = az.load_arviz_data("centered_eight")
+ _coords = {"school": ["Choate", "Lawrenceville"]}
+ az.plot_ess(
+ _idata, kind="local", var_names=["mu", "theta"], coords=_coords
+ )
+ # [az.plot_ess(
+ # _idata, kind="local", var_names=["mu", "theta"], coords=_coords
+ # ), type(az.plot_ess(
+ # _idata, kind="local", var_names=["mu", "theta"], coords=_coords
+ # ))]
+ return
+
+
+def __(az):
+ _non_centered_data = az.load_arviz_data('non_centered_eight')
+ _axes = az.plot_forest(_non_centered_data,
+ kind='forestplot',
+ var_names=["^the"],
+ filter_vars="regex",
+ combined=True,
+ figsize=(9, 7))
+ _axes[0].set_title('Estimated theta for 8 schools model')
+ # [_axes, type(_axes)]
+ return
+
+
+def __(az, np):
+ # time-steps random walk
+ _x_data =np.arange(0,100)
+ # Mean random walk
+ _mu = np.zeros(100)
+ for i in _x_data: _mu[i] = _mu[i-1] + np.random.normal(0, 1, 1)
+ # Simulated pp samples form the random walk time series
+ _y_data = np.random.normal(2 + _mu * 0.5, 0.5, size = (2, 50, 100))
+ # [az.plot_hdi(_x_data, _y_data), type(az.plot_hdi(_x_data, _y_data))]
+ az.plot_hdi(_x_data, _y_data)
+ return i,
+
+
+def __(az, np):
+ _non_centered = az.load_arviz_data('non_centered_eight')
+ _mu_posterior = np.concatenate(_non_centered.posterior["mu"].values)
+ _tau_posterior = np.concatenate(_non_centered.posterior["tau"].values)
+ # [az.plot_kde(_mu_posterior), type(az.plot_kde(_mu_posterior))]
+ az.plot_kde(_mu_posterior)
+ return
+
+
+def __(az):
+ _radon = az.load_arviz_data("radon")
+ _loo_radon = az.loo(_radon, pointwise=True)
+ # [az.plot_khat(_loo_radon, show_bins=True), type(az.plot_khat(_loo_radon, show_bins=True))]
+ az.plot_khat(_loo_radon, show_bins=True)
+ return
+
+
+def __(az):
+ _idata = az.load_arviz_data("radon")
+ # [az.plot_loo_pit(idata=_idata, y="y"), type(az.plot_loo_pit(idata=_idata, y="y"))]
+ az.plot_loo_pit(idata=_idata, y="y")
+ return
+
+
+def __(az, np, xr):
+ _idata = az.load_arviz_data('regression1d')
+ _x = xr.DataArray(np.linspace(0, 1, 100))
+ _idata.posterior["y_model"] = _idata.posterior["intercept"] + _idata.posterior["slope"]*_x
+
+ # [az.plot_lm(idata=_idata, y="y", x=_x), type(az.plot_lm(idata=_idata, y="y", x=_x))]
+ az.plot_lm(idata=_idata, y="y", x=_x)
+ return
+
+
+def __(az):
+ _idata = az.load_arviz_data("centered_eight")
+ _coords = {"school": ["Deerfield", "Lawrenceville"]}
+ # [az.plot_mcse(
+ # _idata, var_names=["mu", "theta"], coords=_coords
+ # ), type(az.plot_mcse(
+ # _idata, var_names=["mu", "theta"], coords=_coords
+ # ))]
+ az.plot_mcse(
+ _idata, var_names=["mu", "theta"], coords=_coords
+ )
+ return
+
+
+def __(az):
+ _centered = az.load_arviz_data('centered_eight')
+ _coords = {'school': ['Choate', 'Deerfield']}
+ # [az.plot_pair(_centered,
+ # var_names=['theta', 'mu', 'tau'],
+ # kind='kde',
+ # coords=_coords,
+ # divergences=True,
+ # textsize=18), type(az.plot_pair(_centered,
+ # var_names=['theta', 'mu', 'tau'],
+ # kind='kde',
+ # coords=_coords,
+ # divergences=True,
+ # textsize=18))]
+ az.plot_pair(_centered,
+ var_names=['theta', 'mu', 'tau'],
+ kind='kde',
+ coords=_coords,
+ divergences=True,
+ textsize=18)
+ return
+
+
+def __(az):
+ _data = az.load_arviz_data('centered_eight')
+ # [az.plot_parallel(_data, var_names=["mu", "tau"]), type(az.plot_parallel(_data, var_names=["mu", "tau"]))]
+ az.plot_parallel(_data, var_names=["mu", "tau"])
+ # plt.show()
+ return
+
+
+def __(az):
+ _data = az.load_arviz_data('centered_eight')
+ # [az.plot_posterior(_data), type(az.plot_posterior(_data))]
+ az.plot_posterior(_data)
+ return
+
+
+def __(az):
+ _data = az.load_arviz_data('radon')
+ # [az.plot_ppc(_data, data_pairs={"y":"y"}), type(az.plot_ppc(_data, data_pairs={"y":"y"}))]
+ az.plot_ppc(_data, data_pairs={"y":"y"})
+ # plt.gca()
+ return
+
+
+def __(az, plt):
+ _data = az.load_arviz_data('centered_eight')
+ # [az.plot_rank(_data), type(az.plot_rank(_data))]
+ az.plot_rank(_data)
+ plt.gca()
+ return
+
+
+def __(az):
+ _idata = az.load_arviz_data('classification10d')
+ # [az.plot_separation(idata=_idata, y='outcome', y_hat='outcome', figsize=(8, 1)), type(az.plot_separation(idata=_idata, y='outcome', y_hat='outcome', figsize=(8, 1)))]
+ az.plot_separation(idata=_idata, y='outcome', y_hat='outcome', figsize=(8, 1))
+ return
+
+
+def __(az):
+ _data = az.load_arviz_data('non_centered_eight')
+ _coords = {'school': ['Choate', 'Lawrenceville']}
+ # [az.plot_trace(_data, var_names=('theta'), filter_vars="like", coords=_coords), type(az.plot_trace(_data, var_names=('theta'), filter_vars="like", coords=_coords))]
+ az.plot_trace(_data, var_names=('theta'), filter_vars="like", coords=_coords)
+ return
+
+
+def __(az, np):
+ _nchains, _ndraws = (4, 500)
+ _obs_data = {
+ "y": 2 * np.arange(1, 9) + 3,
+ "z": 2 * np.arange(8, 12) + 3,
+ }
+ _posterior_predictive = {
+ "y": np.random.normal(
+ (_obs_data["y"] * 1.2) - 3, size=(_nchains, _ndraws, len(_obs_data["y"]))
+ ),
+ "z": np.random.normal(
+ (_obs_data["z"] * 1.2) - 3, size=(_nchains, _ndraws, len(_obs_data["z"]))
+ ),
+ }
+ _idata = az.from_dict(
+ observed_data=_obs_data,
+ posterior_predictive=_posterior_predictive,
+ _coords={"obs_dim": np.arange(1, 9), "pred_dim": np.arange(8, 12)},
+ dims={"y": ["obs_dim"], "z": ["pred_dim"]},
+ )
+ ax = az.plot_ts(idata=_idata, y="y", y_holdout="z")
+ # [ax, type(ax)]
+ ax
+ return ax,
+
+
+def __(az):
+ _data = az.load_arviz_data('centered_eight')
+ az.plot_violin(_data)
+ return
+
+
[email protected](hide_code=True)
+def __():
+ # import libraries
+ import marimo as mo
+ import numpy as np
+ import arviz as az
+ import matplotlib.pyplot as plt
+ import xarray as xr
+ from scipy.stats import uniform, norm
+ return az, mo, norm, np, plt, uniform, xr
+
+
+if __name__ == "__main__":
+ app.run()