From 9818f3ad6bd9b0db04103527ed94e0eda2c1b53d Mon Sep 17 00:00:00 2001 From: VsevolodX Date: Tue, 14 Apr 2026 16:49:06 -0700 Subject: [PATCH] update: handle plotting in pyodide --- utils/plot.py | 26 +++++--------------------- 1 file changed, 5 insertions(+), 21 deletions(-) diff --git a/utils/plot.py b/utils/plot.py index 823d5b85e..8ddfc63ad 100644 --- a/utils/plot.py +++ b/utils/plot.py @@ -1,12 +1,9 @@ -import io -import sys from typing import Dict, List, Tuple, Union -from IPython.display import Image, display from mat3ra.made.material import Material from mat3ra.made.tools.analyze.interface import ZSLMatchHolder from mat3ra.made.tools.analyze.rdf import RadialDistributionFunction -from mat3ra.utils.jupyterlite.plot import plot_distribution_function, scatter_plot_2d +from mat3ra.utils.jupyterlite.plot import plot_distribution_function, render_figure, scatter_plot_2d from matplotlib import pyplot as plt @@ -43,7 +40,7 @@ def plot_strain_vs_area(matches: List["ZSLMatchHolder"], settings: Dict[str, Uni } fig = scatter_plot_2d(x_values, y_values, hover_texts, plot_settings, trace_names) - fig.show() + render_figure(fig) def plot_twisted_interface_solutions(interfaces: List["Material"]) -> None: @@ -70,31 +67,18 @@ def plot_twisted_interface_solutions(interfaces: List["Material"]) -> None: plot_settings = {"x_title": "Twist Angle (°)", "y_title": "Number of Atoms", "title": "Twisted Interface Solutions"} fig = scatter_plot_2d(x_values, y_values, hover_texts, plot_settings, trace_names) - fig.show() + render_figure(fig) def plot_rdf(material: "Material", cutoff: float = 10.0, bin_size: float = 0.1) -> None: """ Plot RDF for a material. """ - is_pyodide = sys.platform == "emscripten" - if is_pyodide: - # This is needed so that plt is adjusted before import to work in Pyodide environment - plt.switch_backend("Agg") - rdf = RadialDistributionFunction.from_material(material, cutoff=cutoff, bin_size=bin_size) plot_distribution_function( rdf.bin_centers, rdf.rdf, xlabel="Distance (Å)", ylabel="g(r)", title="Radial Distribution Function (RDF)" ) - if is_pyodide: - # Necessary to display the plot in Pyodide environment - buf = io.BytesIO() - plt.savefig(buf, format="png") - buf.seek(0) - display(Image(buf.read())) - plt.close() - def plot_series( series: List[Dict], @@ -124,7 +108,7 @@ def plot_series( x_labels = [str(item[x_key]) for item in series] y_values = [item[y_key] for item in series] x_indices = list(range(len(series))) - _, ax = plt.subplots(figsize=figsize) + figure, ax = plt.subplots(figsize=figsize) ax.plot(x_indices, y_values, marker=marker) ax.set_xticks(x_indices) ax.set_xticklabels(x_labels, rotation=rotation, ha="right") @@ -132,4 +116,4 @@ def plot_series( ax.set_ylabel(ylabel) ax.set_title(title) plt.tight_layout() - plt.show() + render_figure(figure)