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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: stop applying the notebook theme to plotting libraries (#11147)
Kiran Gadhave543954874519
diff --git a/docs/guides/configuration/theming.md b/docs/guides/configuration/theming.mdindex 5f0d4ef9e7..40a8ae429f 100644--- a/docs/guides/configuration/theming.md+++ b/docs/guides/configuration/theming.md@@ -71,6 +71,56 @@ In order to force a theme for an application, you can override the marimo config# ///```+## Plot themes++marimo does not change the theme of plotting libraries. In dark mode, plots from [matplotlib](https://matplotlib.org/stable/users/explain/customizing.html#using-style-sheets), [seaborn](https://seaborn.pydata.org/generated/seaborn.set_theme.html), [plotly](https://plotly.com/python/templates/), [bokeh](https://docs.bokeh.org/en/latest/docs/reference/themes.html), and holoviews keep their library default themes, and plots that you save from Python look the same as the plots in the notebook.++Altair charts are the exception. marimo renders them with the Vega dark theme in a dark notebook, but this applies only to the display. Charts that you save with `chart.save()` keep the Altair default theme. A theme that you set with [`alt.theme.enable()`](https://altair-viz.github.io/user_guide/generated/theme/altair.theme.enable.html) takes precedence over the marimo theme.++If you want plots to match a dark notebook, set the theme in the plotting library. `mo.app_meta().theme` returns the current notebook theme. If the notebook theme is `system`, `mo.app_meta().theme` returns `light`, so this check does not detect a dark operating system theme.++=== "matplotlib and seaborn"++ ```python+ import marimo as mo+ import matplotlib.style++ if mo.app_meta().theme == "dark":+ # Seaborn draws with matplotlib, so this style applies to seaborn too.+ matplotlib.style.use("dark_background")+ ```++=== "plotly"++ ```python+ import marimo as mo+ import plotly.io as pio++ if mo.app_meta().theme == "dark":+ pio.templates.default = "plotly_dark"+ ```++=== "bokeh"++ ```python+ import marimo as mo+ from bokeh.io import curdoc++ if mo.app_meta().theme == "dark":+ curdoc().theme = "dark_minimal"+ ```++=== "holoviews"++ ```python+ import marimo as mo+ import holoviews as hv++ if mo.app_meta().theme == "dark":+ # The holoviews renderer accepts the same theme names as bokeh.+ hv.renderer("bokeh").theme = "dark_minimal"+ ```+## Targeting cellsYou can target a cell's styles from the `data-cell-name` attribute. You can also target a cell's output with the `data-cell-role="output"` attribute.diff --git a/docs/guides/working_with_data/plotting.md b/docs/guides/working_with_data/plotting.mdindex d1eac1c1d2..5472fb157d 100644--- a/docs/guides/working_with_data/plotting.md+++ b/docs/guides/working_with_data/plotting.md@@ -13,6 +13,10 @@ marimo automatically sends the selected data back to Python!> For a video overview of reactive plots, check out our [YouTube tutorial](https://youtu.be/KFXsm1wr408).+Plots keep their library default themes in both light and dark notebooks. See+[Plot themes](../configuration/theming.md#plot-themes) if you want plots to+follow the notebook theme.+## Reactive plots! ⚡!!! warning "Requirements"diff --git a/marimo/_output/formatters/altair_formatters.py b/marimo/_output/formatters/altair_formatters.pyindex 4f812f0432..98d364f585 100644--- a/marimo/_output/formatters/altair_formatters.py+++ b/marimo/_output/formatters/altair_formatters.py@@ -6,7 +6,6 @@ import refrom typing import Anyfrom urllib.request import urlopen-from marimo._config.config import Themefrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._loggers import marimo_loggerfrom marimo._messaging.mimetypes import METADATA_KEY, KnownMimeType, MimeBundle@@ -113,11 +112,6 @@ class AltairFormatter(FormatterFactory):chart_to_json(chart=chart, validate=False),)- def apply_theme(self, theme: Theme) -> None:- del theme- # We don't need to apply this here because the theme is set in the- # vega-lite component-def _format_png_mimebundle(png_mimebundle: tuple[MimeBundle, MimeBundle],diff --git a/marimo/_output/formatters/bokeh_formatters.py b/marimo/_output/formatters/bokeh_formatters.pyindex 91f4f32f52..f33fdf576f 100644--- a/marimo/_output/formatters/bokeh_formatters.py+++ b/marimo/_output/formatters/bokeh_formatters.py@@ -4,7 +4,6 @@ from __future__ import annotationsimport functoolsfrom typing import TYPE_CHECKING, Any-from marimo._config.config import Themefrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.builder import hfrom marimo._output.formatters.formatter_factory import FormatterFactory@@ -110,8 +109,3 @@ class BokehFormatter(FormatterFactory):)return unpatch-- def apply_theme(self, theme: Theme) -> None:- from bokeh.io import curdoc # type: ignore-- curdoc().theme = "dark_minimal" if theme == "dark" else None # type: ignorediff --git a/marimo/_output/formatters/formatter_factory.py b/marimo/_output/formatters/formatter_factory.pyindex abdfb27553..85f0152b0f 100644--- a/marimo/_output/formatters/formatter_factory.py+++ b/marimo/_output/formatters/formatter_factory.py@@ -4,11 +4,6 @@ from __future__ import annotationsimport abcfrom collections.abc import Callable-from marimo import _loggers-from marimo._config.config import Theme--LOGGER = _loggers.marimo_logger()-Unregister = Callable[[], None]@@ -36,29 +31,3 @@ class FormatterFactory(abc.ABC):patches."""raise NotImplementedError-- def apply_theme(self, theme: Theme) -> None:- """- Apply the theme (light/dark) to third party libraries.- If the theme is set to "system", then we fallback to "light".-- Args:- theme: The theme to apply.- """- del theme- return-- def apply_theme_safe(self, theme: Theme) -> None:- """- Apply the theme (light/dark) to third party libraries.- If the theme is set to "system", then we fallback to "light".-- Args:- theme: The theme to apply.- """- try:- self.apply_theme(theme)- except Exception as e:- LOGGER.error(- f"Error applying theme {theme} for {self.package_name()}: {e}"- )diff --git a/marimo/_output/formatters/formatters.py b/marimo/_output/formatters/formatters.pyindex 1163a39628..059bbb6f3b 100644--- a/marimo/_output/formatters/formatters.py+++ b/marimo/_output/formatters/formatters.py@@ -5,7 +5,6 @@ import sysfrom typing import TYPE_CHECKING, Anyfrom marimo import _loggers-from marimo._config.config import Themefrom marimo._output.formatters.ai_formatters import (GoogleAiFormatter,OpenAIFormatter,@@ -96,7 +95,6 @@ NATIVE_FACTORIES: Sequence[FormatterFactory] = [def patch_finder(finder: Any,third_party_factories: dict[str, FormatterFactory] | None = None,- theme: Theme = "light",) -> None:"""Patch a MetaPathFinder to register formatters for third-parties.Python's import logic has roughly the following logic:@@ -154,7 +152,6 @@ def patch_finder() -> Any:loader_return_value = original_exec_module(module)factory.register()- factory.apply_theme_safe(theme)return loader_return_valuespec.loader.exec_module = exec_module@@ -176,7 +173,7 @@ def patch_finder(finder.find_spec = find_spec.__get__(finder) # type: ignore[method-assign]-def register_formatters(theme: Theme = "light") -> None:+def register_formatters() -> None:"""Register formatters with marimo.marimo comes packaged with rich formatters for a number of third-party@@ -210,7 +207,6 @@ def register_formatters(theme: Theme = "light") -> None:for package, factory in THIRD_PARTY_FACTORIES.items():if package in sys.modules:factory.register()- factory.apply_theme_safe(theme)pre_registered.add(package)third_party_factories = {@@ -224,14 +220,9 @@ def register_formatters(theme: Theme = "light") -> None:# particular, when its module is exec'd). This ensures that formatters are# loaded at the last possible moment: when its package is imported.for finder in sys.meta_path:- patch_finder(- finder,- third_party_factories=third_party_factories,- theme=theme,- )+ patch_finder(finder, third_party_factories=third_party_factories)# These factories are for builtins or other things that don't require a# package import. So we can register them at program start-up.for factory in NATIVE_FACTORIES:factory.register()- factory.apply_theme_safe(theme)diff --git a/marimo/_output/formatters/holoviews_formatters.py b/marimo/_output/formatters/holoviews_formatters.pyindex c19f6fda20..e669ba2871 100644--- a/marimo/_output/formatters/holoviews_formatters.py+++ b/marimo/_output/formatters/holoviews_formatters.py@@ -2,8 +2,6 @@from __future__ import annotationsfrom marimo import _loggers-from marimo._config.config import Theme-from marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.formatters.formatter_factory import FormatterFactoryfrom marimo._output.formatting import as_html@@ -49,18 +47,3 @@ class HoloViewsFormatter(FormatterFactory):# this may be bokeh, matplotlib, or plotlyhtml = as_html(backend_output)return ("text/html", html.text)-- def apply_theme(self, theme: Theme) -> None:- import holoviews as hv # type: ignore-- # TODO: checking for has() imports the library, which is not ideal,- # but the importing bokeh may come after importing holoviews.- # We can maybe improve this hooking into the holoviews Store.renderers- if DependencyManager.bokeh.has():- hv.renderer("bokeh").theme = (- "dark_minimal" if theme == "dark" else None- )- if DependencyManager.plotly.has():- hv.renderer("plotly").theme = (- "plotly_dark" if theme == "dark" else "plotly"- )diff --git a/marimo/_output/formatters/matplotlib_formatters.py b/marimo/_output/formatters/matplotlib_formatters.pyindex 027180a699..c62828ae12 100644--- a/marimo/_output/formatters/matplotlib_formatters.py+++ b/marimo/_output/formatters/matplotlib_formatters.py@@ -1,7 +1,6 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations-from marimo._config.config import Themefrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.formatters.formatter_factory import FormatterFactory@@ -47,17 +46,3 @@ class MatplotlibFormatter(FormatterFactory):return mime_data_artist(bc.patches[0].figure) # type: ignoreelse:return ("text/plain", str(bc))-- def apply_theme(self, theme: Theme) -> None:- import matplotlib.style # type: ignore-- # Note: we don't set to "default", because that overwrites all- # rcParams.- #- # We also don't try to restore from an rcParams file, because that- # may overwrite other rcParams that the user set.- #- # This means that the style can't be switched from dark to light- # without restarting the kernel.- if theme == "dark":- matplotlib.style.use("dark_background")diff --git a/marimo/_output/formatters/plotly_formatters.py b/marimo/_output/formatters/plotly_formatters.pyindex cfcb5b5f3f..c147973078 100644--- a/marimo/_output/formatters/plotly_formatters.py+++ b/marimo/_output/formatters/plotly_formatters.py@@ -4,7 +4,6 @@ from __future__ import annotationsimport jsonfrom typing import Any-from marimo._config.config import Themefrom marimo._messaging.cell_output import CellChannelfrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._messaging.notification_utils import CellNotificationUtils@@ -98,8 +97,3 @@ class PlotlyFormatter(FormatterFactory):args={"figure": json, "config": resolved_config},))-- def apply_theme(self, theme: Theme) -> None:- import plotly.io as pio # type: ignore-- pio.templates.default = "plotly_dark" if theme == "dark" else "plotly"diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.pyindex edbc404d7e..6149de6d84 100644--- a/marimo/_pyodide/pyodide_session.py+++ b/marimo/_pyodide/pyodide_session.py@@ -544,7 +544,7 @@ def _launch_pyodide_kernel(teardown_kernel,)- register_formatters(theme=user_config["display"]["theme"])+ register_formatters()LOGGER.debug("Launching pyodide kernel")# Patches for pyodide compatibilitydiff --git a/marimo/_runtime/app/script_runner.py b/marimo/_runtime/app/script_runner.pyindex c8acb2ed73..45c97a13c2 100644--- a/marimo/_runtime/app/script_runner.py+++ b/marimo/_runtime/app/script_runner.py@@ -239,9 +239,7 @@ class AppScriptRunner:from marimo._output.formatting import FORMATTERSif not FORMATTERS.is_empty():- register_formatters(- theme=get_context().marimo_config["display"]["theme"]- )+ register_formatters()post_execute_hooks: list[Callable[[], Any]] = []if DependencyManager.matplotlib.has():diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex a4d7d23aaa..ee03235467 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -2623,14 +2623,13 @@ def _create_streams(def _install_subprocess_handlers(kernel: Kernel,- user_config: MarimoConfig,interrupt_queue: QueueType[bool] | None,) -> None:# Subprocess kernels don't share state with the host, so they need# their own formatter import hooks and signal handlers.from marimo._output.formatters.formatters import register_formatters- register_formatters(theme=user_config["display"]["theme"])+ register_formatters()signal.signal(signal.SIGINT, handlers.construct_interrupt_handler())@@ -2712,11 +2711,7 @@ def launch_kernel(kernel.start_out_of_band_worker(completion_queue)if is_subprocess:- # Read theme from kernel.user_config — create_kernel may have- # mutated it for run mode (autorun + auto_reload off).- _install_subprocess_handlers(- kernel, kernel.user_config, interrupt_queue- )+ _install_subprocess_handlers(kernel, interrupt_queue)# The control loop is asynchronous so that (a) user code can use# top-level await, and (b) background asyncio tasks created bydiff --git a/marimo/_session/managers/kernel.py b/marimo/_session/managers/kernel.pyindex ee039bcdad..8cd722065a 100644--- a/marimo/_session/managers/kernel.py+++ b/marimo/_session/managers/kernel.py@@ -115,10 +115,9 @@ class KernelManagerImpl(KernelManager):) -> None:runtime.launch_kernel(*args)- # install formatter import hooks, which will be shared by all- # threads (in edit mode, the single kernel process installs- # formatters ...)- register_formatters(theme=self.config_manager.theme)+ # Install formatter import hooks once in the host process. Every+ # kernel thread shares them.+ register_formatters()if self.redirect_console_to_browser:from marimo._messaging.thread_local_streams import (diff --git a/marimo/_smoke_tests/theming/apply_theme.py b/marimo/_smoke_tests/theming/apply_theme.pydeleted file mode 100644index af5397a378..0000000000--- a/marimo/_smoke_tests/theming/apply_theme.py+++ /dev/null@@ -1,164 +0,0 @@-# /// script-# requires-python = ">=3.11"-# dependencies = [-# "seaborn",-# "matplotlib",-# "holoviews",-# "bokeh",-# "vega-datasets",-# "altair",-# "plotly",-# "marimo",-# "pandas",-# "numpy",-# ]-# ///--import marimo--__generated_with = "0.15.5"-app = marimo.App(width="medium")---def _(mo):- mo.app_meta().theme- return---def _(mo):- mo.md(r"""# Seaborn""")- return---def _(df, plt):- import seaborn as sns-- plt.figure(figsize=(10, 6))- sns.lineplot(x="x", y="y", data=df)- plt.title("Seaborn: Sine Wave")- return---def _(mo):- mo.md(r"""# Matplotlib""")- return---def _(x, y):- import matplotlib.pyplot as plt-- plt.figure(figsize=(10, 6))- plt.plot(x, y)- plt.title("Matplotlib: Sine Wave")- return (plt,)--[email protected](hide_code=True)-def _(mo):- mo.md(r"""# Holoviews""")- return---def _(df):- import holoviews as hv-- hv.extension("bokeh")- curve = hv.Curve(df, "x", "y")- hv.render(curve.opts(title="Holoviews: Sine Wave", width=800, height=400))- return--[email protected](hide_code=True)-def _(mo):- mo.md(r"""# Bokeh""")- return---def _(x, y):- # Bokeh- from bokeh.plotting import figure, show-- p = figure(- title="Bokeh: Sine Wave",- x_axis_label="x",- y_axis_label="y",- width=800,- height=400,- )- p.line(x, y, line_width=2)- p- return--[email protected](hide_code=True)-def _(mo):- mo.md(r"""# Altair""")- return--[email protected](hide_code=True)-def _(mo):- import altair as alt- from vega_datasets import data-- chart = (- alt.Chart(data.cars())- .mark_point()- .encode(- x="Horsepower",- y="Miles_per_Gallon",- color="Origin",- )- )-- chart = mo.ui.altair_chart(chart)- chart- return--[email protected](hide_code=True)-def _(mo):- mo.md(r"""# Plotly""")- return--[email protected](hide_code=True)-def _(df):- # Plotly- import plotly.express as px-- px.line(df, x="x", y="y", title="Plotly: Sine Wave")- return---def _(np, pd):- # Sample data- x = np.linspace(0, 10, 100)- y = np.sin(x)- df = pd.DataFrame({"x": x, "y": y})- return df, x, y---def _():- import marimo as mo- return (mo,)---def _():- import numpy as np- import pandas as pd- return np, pd---if __name__ == "__main__":- app.run()diff --git a/tests/_output/formatters/test_matplotlib.py b/tests/_output/formatters/test_matplotlib.pyindex 6f3aef8071..1f11936b39 100644--- a/tests/_output/formatters/test_matplotlib.py+++ b/tests/_output/formatters/test_matplotlib.py@@ -1,12 +1,15 @@from __future__ import annotationsimport base64+import copyimport jsonimport pytest+from marimo._config.config import DEFAULT_CONFIGfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._runtime.runtime import Kernel+from tests._runtime._helpers.session import mocked_kernel_sessionfrom tests.conftest import ExecReqProviderHAS_MPL = DependencyManager.matplotlib.has()@@ -22,7 +25,7 @@ async def test_matplotlib_rc_light(plt.rcParams["font.family"] = ["monospace"]- register_formatters(theme="light")+ register_formatters()await executing_kernel.run([@@ -42,32 +45,40 @@ async def test_matplotlib_rc_light(@pytest.mark.skipif(not HAS_MPL, reason="optional dependencies not installed")-async def test_matplotlib_rc_dark(- executing_kernel: Kernel, exec_req: ExecReqProvider+async def test_matplotlib_rc_ignores_dark_theme(+ exec_req: ExecReqProvider,) -> None:+ """A dark notebook theme leaves the matplotlib style untouched."""import matplotlib.pyplot as plt # type: ignorefrom marimo._output.formatters.formatters import register_formattersplt.rcParams["font.family"] = ["monospace"]- register_formatters(theme="dark")+ user_config = copy.deepcopy(DEFAULT_CONFIG)+ user_config["display"]["theme"] = "dark"- await executing_kernel.run(- [- exec_req.get(- """- import matplotlib.pyplot as plt+ with mocked_kernel_session(user_config=user_config) as tk:+ register_formatters()- rcParams = plt.rcParams- """- )- ]- )+ await tk.kernel.run(+ [+ exec_req.get(+ """+ import marimo as mo+ import matplotlib.pyplot as plt- rcParams = executing_kernel.globals["rcParams"]- assert rcParams["font.family"] == ["monospace"]- assert rcParams["figure.facecolor"] == "black"+ theme = mo.app_meta().theme+ rcParams = plt.rcParams+ """+ )+ ]+ )++ assert tk.kernel.globals["theme"] == "dark"+ rcParams = tk.kernel.globals["rcParams"]+ assert rcParams["font.family"] == ["monospace"]+ assert rcParams["figure.facecolor"] == "white"def _extract_png_dimensions(data_url: str) -> tuple[int, int]:@@ -93,7 +104,7 @@ async def test_matplotlib_image_resolution_uses_retina_scale("""Test that PNG output uses retina scaling without mutating DPI."""from marimo._output.formatters.formatters import register_formatters- register_formatters(theme="light")+ register_formatters()await executing_kernel.run([@@ -155,7 +166,7 @@ async def test_matplotlib_display_size_remains_constant("""Test that the display size in the notebook remains constant even if DPI changes."""from marimo._output.formatters.formatters import register_formatters- register_formatters(theme="light")+ register_formatters()await executing_kernel.run([@@ -209,7 +220,7 @@ async def test_matplotlib_backwards_compatibility("""Test that existing matplotlib code still works with the new DPI rendering logic."""from marimo._output.formatters.formatters import register_formatters- register_formatters(theme="light")+ register_formatters()# Test various matplotlib output typesawait executing_kernel.run(@@ -256,7 +267,7 @@ async def test_matplotlib_svg_rendering("""Test that matplotlib figures are rendered in SVG format."""from marimo._output.formatters.formatters import register_formatters- register_formatters(theme="light")+ register_formatters()await executing_kernel.run([@@ -293,7 +304,7 @@ async def test_matplotlib_svg_rendering_in_layout("""Test that the SVG output can be used in a layout."""from marimo._output.formatters.formatters import register_formatters- register_formatters(theme="light")+ register_formatters()await executing_kernel.run([diff --git a/tests/_output/formatters/test_plotly_formatters.py b/tests/_output/formatters/test_plotly_formatters.pyindex 83425ac2c2..6bef22c0f7 100644--- a/tests/_output/formatters/test_plotly_formatters.py+++ b/tests/_output/formatters/test_plotly_formatters.py@@ -1,18 +1,55 @@from __future__ import annotations+import copyimport jsonimport pytest+from marimo._config.config import DEFAULT_CONFIGfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._output.formatters.formatters import register_formattersfrom marimo._output.formatters.plotly_formatters import PlotlyFormatterfrom marimo._output.formatting import get_formatter+from tests._runtime._helpers.session import mocked_kernel_session+from tests.conftest import ExecReqProviderHAS_DEPS = DependencyManager.plotly.has()HAS_ANYWIDGET = DependencyManager.anywidget.has()[email protected](not HAS_DEPS, reason="plotly not installed")+async def test_plotly_template_ignores_dark_theme(+ exec_req: ExecReqProvider, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A dark notebook theme leaves the plotly default template untouched."""+ import plotly.io as pio++ monkeypatch.setattr(pio.templates, "default", "plotly")++ user_config = copy.deepcopy(DEFAULT_CONFIG)+ user_config["display"]["theme"] = "dark"++ with mocked_kernel_session(user_config=user_config) as tk:+ register_formatters()++ await tk.kernel.run(+ [+ exec_req.get(+ """+ import marimo as mo+ import plotly.io as pio++ theme = mo.app_meta().theme+ template = pio.templates.default+ """+ )+ ]+ )++ assert tk.kernel.globals["theme"] == "dark"+ assert tk.kernel.globals["template"] == "plotly"++@pytest.mark.skipif(not HAS_DEPS, reason="plotly not installed")def test_plotly_config_forwarding():"""Test that config parameter is properly forwarded"""