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.

feat: add support for holoviews (#752)

Myles Scolnick154f02f0ffc5
diff --git a/docs/api/plotting.md b/docs/api/plotting.md
index bd44d5abcc..8eda1f970c 100644
--- a/docs/api/plotting.md
+++ b/docs/api/plotting.md
@@ -20,8 +20,21 @@ For more information about plotting, see the [plotting guide](../guides/plotting
.. autofunction:: marimo.ui.plotly
```
-## matplotlib
+## Interactive matplotlib
```{eval-rst}
.. autofunction:: marimo.mpl.interactive
```
+
+## Other plotting libraries
+
+You can use all the popular plotting libraries with marimo. Such as:
+
+- [Matplotlib](https://matplotlib.org/)
+- [Plotly](https://plotly.com/)
+- [Seaborn](https://seaborn.pydata.org/)
+- [Bokeh](https://bokeh.org/)
+- [Altair](https://altair-viz.github.io/)
+- [HoloViews](http://holoviews.org/)
+- [hvPlot](https://hvplot.holoviz.org/)
+- [Leafmap](https://leafmap.org/)
diff --git a/marimo/_output/formatters/bokeh_formatters.py b/marimo/_output/formatters/bokeh_formatters.py
new file mode 100644
index 0000000000..e034922821
--- /dev/null
+++ b/marimo/_output/formatters/bokeh_formatters.py
@@ -0,0 +1,39 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import marimo._output.data.data as mo_data
+from marimo._messaging.mimetypes import KnownMimeType
+from marimo._output.formatters.formatter_factory import FormatterFactory
+from marimo._output.utils import flatten_string
+
+
+class BokehFormatter(FormatterFactory):
+ @staticmethod
+ def package_name() -> str:
+ return "bokeh"
+
+ def register(self) -> None:
+ import bokeh.models # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+
+ from marimo._output import formatting
+
+ @formatting.formatter(bokeh.models.Model)
+ def _show_plot(
+ plot: bokeh.models.Model,
+ ) -> tuple[KnownMimeType, str]:
+ import bokeh.embed # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+ import bokeh.resources # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+
+ html = bokeh.embed.file_html(plot, bokeh.resources.CDN)
+ html_file = mo_data.html(html)
+ return (
+ "text/html",
+ (
+ flatten_string(
+ f"<iframe src='{html_file.url}'"
+ "frameborder='0' scrolling='auto'"
+ "style='width: 100%'"
+ "onload='__resizeIframe(this)'></iframe>"
+ )
+ ),
+ )
diff --git a/marimo/_output/formatters/formatters.py b/marimo/_output/formatters/formatters.py
index 5f79c92fdd..260646876d 100644
--- a/marimo/_output/formatters/formatters.py
+++ b/marimo/_output/formatters/formatters.py
@@ -5,7 +5,9 @@ import sys
from typing import Any, Callable, Sequence
from marimo._output.formatters.altair_formatters import AltairFormatter
+from marimo._output.formatters.bokeh_formatters import BokehFormatter
from marimo._output.formatters.formatter_factory import FormatterFactory
+from marimo._output.formatters.holoviews_formatters import HoloViewsFormatter
from marimo._output.formatters.leafmap_formatters import LeafmapFormatter
from marimo._output.formatters.matplotlib_formatters import MatplotlibFormatter
from marimo._output.formatters.pandas_formatters import PandasFormatter
@@ -23,6 +25,8 @@ THIRD_PARTY_FACTORIES: dict[str, FormatterFactory] = {
PlotlyFormatter.package_name(): PlotlyFormatter(),
SeabornFormatter.package_name(): SeabornFormatter(),
LeafmapFormatter.package_name(): LeafmapFormatter(),
+ BokehFormatter.package_name(): BokehFormatter(),
+ HoloViewsFormatter.package_name(): HoloViewsFormatter(),
}
# Formatters for builtin types and other things that don't require a
diff --git a/marimo/_output/formatters/holoviews_formatters.py b/marimo/_output/formatters/holoviews_formatters.py
new file mode 100644
index 0000000000..a64f58fa58
--- /dev/null
+++ b/marimo/_output/formatters/holoviews_formatters.py
@@ -0,0 +1,41 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._messaging.mimetypes import KnownMimeType
+from marimo._output.formatters.formatter_factory import FormatterFactory
+from marimo._output.formatters.plotly_formatters import PlotlyFormatter
+from marimo._output.formatting import as_html
+
+
+class HoloViewsFormatter(FormatterFactory):
+ @staticmethod
+ def package_name() -> str:
+ return "holoviews"
+
+ def register(self) -> None:
+ import holoviews as hv # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+
+ from marimo._output import formatting
+
+ @formatting.formatter(hv.core.ViewableElement)
+ def _show_chart(
+ plot: hv.core.ViewableElement,
+ ) -> tuple[KnownMimeType, str]:
+ backend_output = hv.render(plot)
+
+ # If its a dict, then its a plotly figure,
+ # and we should convert it to a plotly object
+ if DependencyManager.has_plotly() and isinstance(
+ backend_output, dict
+ ):
+ plotly_html = PlotlyFormatter.render_plotly_dict(
+ backend_output
+ )
+ return ("text/html", plotly_html.text)
+
+ # Call as_html to recurse back into the formatter
+ # this may be bokeh, matplotlib, or plotly
+ html = as_html(backend_output)
+
+ return ("text/html", html.text)
diff --git a/marimo/_output/formatters/plotly_formatters.py b/marimo/_output/formatters/plotly_formatters.py
index 9ab32e30a4..fe012d58cc 100644
--- a/marimo/_output/formatters/plotly_formatters.py
+++ b/marimo/_output/formatters/plotly_formatters.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import json
+from typing import Any
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.formatters.formatter_factory import FormatterFactory
@@ -24,11 +25,15 @@ class PlotlyFormatter(FormatterFactory):
def _show_plotly_figure(
fig: plotly.graph_objects.Figure,
) -> tuple[KnownMimeType, str]:
- json_str = plotly.io.to_json(fig)
- plugin = Html(
- build_stateless_plugin(
- component_name="marimo-plotly",
- args={"figure": json.loads(json_str)},
- )
- )
+ json_str: str = plotly.io.to_json(fig)
+ plugin = PlotlyFormatter.render_plotly_dict(json.loads(json_str))
return ("text/html", plugin.text)
+
+ @staticmethod
+ def render_plotly_dict(json: dict[Any, Any]) -> Html:
+ return Html(
+ build_stateless_plugin(
+ component_name="marimo-plotly",
+ args={"figure": json},
+ )
+ )
diff --git a/marimo/_smoke_tests/third_party/holoviews.py b/marimo/_smoke_tests/third_party/holoviews.py
new file mode 100644
index 0000000000..56945be037
--- /dev/null
+++ b/marimo/_smoke_tests/third_party/holoviews.py
@@ -0,0 +1,101 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.2.2"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ """
+ # HoloViews in marimo
+ ```
+ pip install holoviews
+ ```
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+ import numpy as np
+ import holoviews as hv
+ from holoviews import opts
+ import marimo as mo
+
+ hv.extension("bokeh", "plotly", "matplotlib")
+ return hv, mo, np, opts, pd
+
+
+def __(pd):
+ station_info = pd.read_csv(
+ "https://raw.githubusercontent.com/holoviz/holoviews/main/examples/assets/station_info.csv"
+ )
+ return station_info,
+
+
+def __(hv, mo):
+ backend = mo.ui.dropdown(
+ options=list(hv.extension._backends.keys()),
+ label="Choose your backend",
+ full_width=True,
+ )
+ return backend,
+
+
+def __(backend, hv, mo, station_info):
+ scatter = hv.Scatter(station_info, "services", "ridership")
+ if backend.value:
+ hv.extension(backend.value)
+ mo.hstack([backend, scatter], align="center")
+ return scatter,
+
+
+def __(mo):
+ mo.md("## Area chart")
+ return
+
+
+def __(hv, np):
+ xs = np.linspace(0, np.pi * 4, 40)
+ hv.Area((xs, np.sin(xs)))
+ return xs,
+
+
+def __(mo):
+ mo.md("## Scatter chart")
+ return
+
+
+def __(scatter):
+ scatter
+ return
+
+
+def __(mo):
+ mo.md("# HV Plot")
+ return
+
+
+def __():
+ import hvplot.pandas
+ from bokeh.sampledata.penguins import data as df
+
+ df.hvplot.scatter(x='bill_length_mm', y='bill_depth_mm', by='species')
+ return df, hvplot
+
+
+if __name__ == "__main__":
+ app.run()