From 2b186aa125ff1e263491b424224d7be98235cf08 Mon Sep 17 00:00:00 2001 From: javoha Date: Thu, 3 Dec 2026 15:38:25 +0100 Subject: [PATCH] 2D plots: draw into given axes, optional show, return the figure All matplotlib 2D plots of the Workbench take ax (axes to draw into, e.g. one subplot) and show (False: return without showing, to add to the plot first), and return (fig, ax), like the 3D plots already take show and return their plotter: - plot_structural_model_2D, plot_fault_model_2D - plot_cross_section_2D (axes: two axes, one per panel; returns (fig, axes)), plot_cross_section_difference_2D - plot_variable_along_line, plot_variable_time_series Defaults are unchanged (new figure, shown), so the Workbench inspectors behave as before. A figure the plot creates is laid out as before; a caller's figure is left for the caller to arrange. Shared helpers in core/utility/figures.py. Along-line and fault-domain colorbar no longer use pyplot's current figure. Use case: model sections drawn on top of an outcrop photo, and method comparisons in one subplot grid (a student's notebooks needed a local backend change for this, which a later merge dropped). Manuals list the options with examples; tests cover drawing into given axes, show=False and the default. Co-Authored-By: Claude Opus 5.5 --- .../simulation_visualization.py | 68 +++++++++++++------ .../structural_modeling_visualization.py | 38 ++++++++--- core/utility/figures.py | 26 +++++++ .../simulation/Manual_simulation.md | 13 ++++ .../Manual_structural_modeling.md | 17 ++++- .../test_simulation_visualization.py | 36 ++++++++++ .../test_visualization_2d.py | 30 ++++++++ 7 files changed, 199 insertions(+), 29 deletions(-) create mode 100644 core/utility/figures.py diff --git a/core/simulation_components/simulation_visualization/simulation_visualization.py b/core/simulation_components/simulation_visualization/simulation_visualization.py index beb228f4..a32f1e8c 100644 --- a/core/simulation_components/simulation_visualization/simulation_visualization.py +++ b/core/simulation_components/simulation_visualization/simulation_visualization.py @@ -23,6 +23,7 @@ from matplotlib.ticker import FormatStrFormatter, MaxNLocator from core.object_components import SimulationResults +from core.utility.figures import figure_and_axes, finish_figure from core.simulation_components.simulation_visualization.material_preview import ( # noqa: F401 (re-export) plot_builder_materials, ) @@ -636,7 +637,9 @@ def plot_cross_section_2D( cmap: str = "coolwarm", n_contours: int = 15, resolution: int = 200, -) -> None: + axes: Optional[Sequence[plt.Axes]] = None, + show: bool = True, +) -> Tuple[plt.Figure, Sequence[plt.Axes]]: """ Slice var_name at two time steps on the same plane and plot them side by side with matplotlib -- filled contours plus contour lines, sharing one @@ -664,6 +667,10 @@ def plot_cross_section_2D( T_bottom]-type background range, so a real but modest change can still be subtle here -- see plot_cross_section_difference_2D for a version that isolates just the change itself. + + axes: two matplotlib axes (e.g. two subplots of a larger figure) to draw + the panels into instead of a new figure. show=False returns without + showing, so more can be added. Returns (fig, axes). """ times = sorted(sim.nodes_by_time.keys()) if not times: @@ -686,7 +693,12 @@ def plot_cross_section_2D( vmax = float(np.nanmax([np.nanmax(Za), np.nanmax(Zb)])) levels = np.linspace(vmin, vmax, n_contours) - fig, axes = plt.subplots(1, 2, figsize=(12, 5), sharex=True, sharey=True) + if axes is None: + fig, axes = plt.subplots(1, 2, figsize=(12, 5), sharex=True, sharey=True) + else: + if len(axes) != 2: + raise ValueError(f"axes must be two axes, one per time step; got {len(axes)}.") + fig = axes[0].figure last_cf = None for ax, Z, t in zip(axes, (Za, Zb), (time_a, time_b)): last_cf = ax.contourf(UG, VG, Z, levels=levels, cmap=cmap, vmin=vmin, vmax=vmax) @@ -699,7 +711,9 @@ def plot_cross_section_2D( fig.colorbar(last_cf, ax=axes, orientation="vertical", label=_variable_label(var_name), fraction=0.046, pad=0.04) fig.suptitle(f"{_variable_label(var_name)} cross-section (origin={_format_point(origin)}, normal={_format_point(normal)}): initial vs final") - plt.show() + if show: + plt.show() + return fig, axes def plot_cross_section_difference_2D( @@ -712,7 +726,9 @@ def plot_cross_section_difference_2D( cmap: str = "RdBu_r", n_contours: int = 15, resolution: int = 200, -) -> None: + ax: Optional[plt.Axes] = None, + show: bool = True, +) -> Tuple[plt.Figure, plt.Axes]: """ Single-panel 2D cross-section of value(time_b) - value(time_a) (default: first/last saved step), diverging colormap symmetric around zero. Unlike @@ -722,6 +738,9 @@ def plot_cross_section_difference_2D( background out entirely and shows only what actually moved, so the change's own spatial pattern (e.g. tracking a fold/unconformity) is not competing visually with the dominant vertical gradient. + + ax draws into existing axes instead of a new figure; show=False returns + without showing. Returns (fig, ax). """ times = sorted(sim.nodes_by_time.keys()) if not times: @@ -746,7 +765,7 @@ def plot_cross_section_difference_2D( max_abs = 1.0 # degenerate all-zero diff -- avoid a zero-width color range levels = np.linspace(-max_abs, max_abs, n_contours) - fig, ax = plt.subplots(figsize=(7, 5)) + fig, ax, own_figure = figure_and_axes(ax, figsize=(7, 5)) cf = ax.contourf(UG, VG, Z, levels=levels, cmap=cmap, vmin=-max_abs, vmax=max_abs) cs = ax.contour(UG, VG, Z, levels=levels, colors="k", linewidths=0.5) ax.clabel(cs, inline=True, fontsize=7, fmt="%.1f") @@ -755,7 +774,8 @@ def plot_cross_section_difference_2D( ax.set_aspect("equal") fig.colorbar(cf, ax=ax, orientation="vertical", label=f"Δ {_variable_label(var_name)}", fraction=0.046, pad=0.04) fig.suptitle(f"Δ {_variable_label(var_name)} cross-section (origin={_format_point(origin)}, normal={_format_point(normal)}): step {_time_step_index(sim, time_a)} -> step {_time_step_index(sim, time_b)}") - plt.show() + finish_figure(fig, own_figure, show, tight=False) + return fig, ax # ---------------------------------------------------------------------- @@ -773,11 +793,16 @@ def plot_variable_along_line( p0: Tuple[float, float, float], p1: Tuple[float, float, float], n_samples: int = 200, -) -> None: + ax: Optional[plt.Axes] = None, + show: bool = True, +) -> Tuple[plt.Figure, plt.Axes]: """ Sample var_name along the straight line from p0 to p1 at one time step and plot it against distance along the line (via PyVista's own pv.Line(...).sample(grid), which linearly interpolates from the mesh). + + ax draws into existing axes (e.g. to compare several lines or time steps + in one plot); show=False returns without showing. Returns (fig, ax). """ _validate_saved_time(sim, time, "time") var_name = _resolve_var_name(sim, time, var_name) @@ -801,14 +826,14 @@ def plot_variable_along_line( values = np.where(valid.reshape((-1,) + (1,) * (values.ndim - 1)), values, np.nan) distances = sampled["Distance"] - plt.figure(figsize=(7, 4)) - plt.plot(distances, values, "-k") - plt.xlabel("Distance along line") - plt.ylabel(_variable_label(var_name)) - plt.title(f"{_variable_label(var_name)} along line at time step {_time_step_index(sim, time)}") - plt.grid(True) - plt.tight_layout() - plt.show() + fig, ax, own_figure = figure_and_axes(ax, figsize=(7, 4)) + ax.plot(distances, values, "-k") + ax.set_xlabel("Distance along line") + ax.set_ylabel(_variable_label(var_name)) + ax.set_title(f"{_variable_label(var_name)} along line at time step {_time_step_index(sim, time)}") + ax.grid(True) + finish_figure(fig, own_figure, show) + return fig, ax def _sample_point_on_mesh( @@ -862,12 +887,17 @@ def plot_variable_time_series( decimals: int = 3, time_step_start: Optional[int] = None, time_step_end: Optional[int] = None, -) -> None: + ax: Optional[plt.Axes] = None, + show: bool = True, +) -> Tuple[plt.Figure, plt.Axes]: """ Sample var_name at a single point across every saved time step and plot the time series. A point outside the mesh's bounds at a given step is plotted as a gap (NaN) rather than raising, so one bad step doesn't prevent seeing the rest of the series. + + ax draws into existing axes (e.g. to compare several points in one plot); + show=False returns without showing. Returns (fig, ax). """ times = sorted(sim.nodes_by_time.keys()) if not times: @@ -914,7 +944,7 @@ def plot_variable_time_series( if np.all(np.isnan(values)): raise ValueError(f"Point {_format_point(point)} lies outside the mesh ({_format_bounds(mesh.bounds)}).") - fig, ax = plt.subplots(figsize=(7, 4)) + fig, ax, own_figure = figure_and_axes(ax, figsize=(7, 4)) ax.plot(range(start, end + 1), values, "-o", color="tab:red") ax.set_xlabel("Time step") ax.set_ylabel(_variable_label(var_name)) @@ -922,5 +952,5 @@ def plot_variable_time_series( ax.grid(True) ax.xaxis.set_major_locator(MaxNLocator(integer=True)) # steps are whole numbers ax.yaxis.set_major_formatter(FormatStrFormatter(f"%.{decimals}f")) - plt.tight_layout() - plt.show() + finish_figure(fig, own_figure, show) + return fig, ax diff --git a/core/structural_modeling_components/structural_modeling_visualization/structural_modeling_visualization.py b/core/structural_modeling_components/structural_modeling_visualization/structural_modeling_visualization.py index 97ba7b32..c3735a08 100644 --- a/core/structural_modeling_components/structural_modeling_visualization/structural_modeling_visualization.py +++ b/core/structural_modeling_components/structural_modeling_visualization/structural_modeling_visualization.py @@ -16,6 +16,7 @@ OctreeGrid, ) from core.structural_modeling_components.structural_modeling_utility.surface_mesh_gradients import normalize_vectors +from core.utility.figures import figure_and_axes, finish_figure from core.structural_modeling_components.structural_objects.structural_objects import ( FaultFrame, StructuralFrame, @@ -528,7 +529,9 @@ def plot_structural_model_2D( show_input_data: bool = True, show_grid: bool = False, title_suffix: str = "", -) -> None: + ax: Optional[plt.Axes] = None, + show: bool = True, +) -> Tuple[plt.Figure, plt.Axes]: """ 2D slice plot of a structural model showing lithology block, scalar contours, and input data. @@ -552,6 +555,17 @@ def plot_structural_model_2D( grid, cells of different sizes on an octree. title_suffix : str, default "" Optional string appended to the plot title. + ax : matplotlib Axes, optional + Draw into these axes (e.g. one subplot of a larger figure) instead of + a new figure. The caller then arranges and shows the figure. + show : bool, default True + Show the figure. Pass False to add to the plot before showing it, + e.g. an image or extra lines drawn into the returned axes. + + Returns + ------- + (fig, ax) + The figure and the axes the section was drawn into. """ warnings.simplefilter("always", UserWarning) @@ -591,7 +605,7 @@ def plot_structural_model_2D( ) x_coords, y_coords = np.meshgrid(x, y, indexing='ij') - fig, ax = plt.subplots(figsize=(10, 6)) + fig, ax, own_figure = figure_and_axes(ax, figsize=(10, 6)) # ---- lithology (optional) ---- if show_result: @@ -703,8 +717,8 @@ def plot_structural_model_2D( ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) - plt.tight_layout() - plt.show() + finish_figure(fig, own_figure, show) + return fig, ax def plot_fault_model_3D( @@ -997,7 +1011,9 @@ def plot_fault_model_2D( show_input_data: bool = True, show_fault_contours: bool = True, show_grid: bool = False, -) -> None: + ax: Optional[plt.Axes] = None, + show: bool = True, +) -> Tuple[plt.Figure, plt.Axes]: """ 2D slice plot for a FaultFrame. @@ -1014,6 +1030,10 @@ def plot_fault_model_2D( Extent is computed from the cell-center coordinates with half-cell padding, so imshow/contour align properly. On an octree, ``index`` and the centers refer to the finest resolution. + + ``ax`` draws into existing axes (e.g. a subplot) instead of a new figure; + ``show=False`` returns without showing, so more can be added to the plot. + Returns ``(fig, ax)``. """ assert axis in ("x", "y", "z"), "Axis must be 'x', 'y', or 'z'." @@ -1065,7 +1085,7 @@ def plot_fault_model_2D( UserWarning, ) - fig, ax = plt.subplots(figsize=(10, 6)) + fig, ax, own_figure = figure_and_axes(ax, figsize=(10, 6)) # --------------------------- # RESULTS: domain map @@ -1091,7 +1111,7 @@ def plot_fault_model_2D( norm=norm, alpha=1.0, ) - cbar = plt.colorbar(im, ax=ax, ticks=domain_values) + cbar = fig.colorbar(im, ax=ax, ticks=domain_values) cbar.set_label("Fault Domain") if show_grid: @@ -1198,5 +1218,5 @@ def plot_fault_model_2D( ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) - plt.tight_layout() - plt.show() + finish_figure(fig, own_figure, show) + return fig, ax diff --git a/core/utility/figures.py b/core/utility/figures.py new file mode 100644 index 00000000..12efa24b --- /dev/null +++ b/core/utility/figures.py @@ -0,0 +1,26 @@ +"""Shared figure handling of the 2D (matplotlib) plots. + +Every 2D plot can draw into existing axes (``ax``, e.g. one subplot of a +larger figure) and can skip showing the figure (``show=False``), so callers +can add to it, such as an outcrop photo below a model section. The plots +return their figure and axes. +""" +from typing import Optional, Tuple + +import matplotlib.pyplot as plt + + +def figure_and_axes(ax: Optional[plt.Axes], figsize: Tuple[float, float]) -> Tuple[plt.Figure, plt.Axes, bool]: + """The given axes and their figure, or a new figure; the flag says whether the figure is new.""" + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + return fig, ax, True + return ax.figure, ax, False + + +def finish_figure(fig: plt.Figure, own_figure: bool, show: bool, tight: bool = True) -> None: + """Lay out a figure the plot created itself (a caller's figure is the caller's to arrange) and show it.""" + if own_figure and tight: + fig.tight_layout() + if show: + plt.show() diff --git a/docs/components/simulation/Manual_simulation.md b/docs/components/simulation/Manual_simulation.md index 9d900298..b44b4ef8 100644 --- a/docs/components/simulation/Manual_simulation.md +++ b/docs/components/simulation/Manual_simulation.md @@ -1091,6 +1091,17 @@ The relevant parameters in the codebase are: - **`n_contours`** *(default: `15`)*: Number of contour levels. - **`resolution`** *(default: `200`)*: Resolution of the interpolated 2D grid used for plotting. +- **`axes`** *(optional, Python only)*: Two matplotlib axes to draw the + two panels into, e.g. subplots of a larger figure. Default `None` + (a new figure). +- **`show`** *(optional, Python only, default: `True`)*: Show the + figure. Set `False` to add to the plot first. + +The function returns `(fig, axes)`. All 2D simulation plots +(`plot_cross_section_difference_2D`, `plot_variable_along_line`, +`plot_variable_time_series`) take `ax` (one axes) and `show` the same +way and return `(fig, ax)`, so several of them can share one figure, for +example temperature logs of several time steps in one plot. The Workbench inspector shows axis-aligned sections, like the structural 2D plots: choose the **`axis`** (x, y or z) and a **`position`** along it @@ -1263,6 +1274,8 @@ The relevant parameters are: - **`n_contours`** *(default: `15`)*: Number of contour levels. - **`resolution`** *(default: `200`)*: Resolution of the interpolated 2D grid. +- **`ax`**, **`show`** *(optional)*: Draw into existing axes / skip + showing, as for `plot_cross_section_2D`; returns `(fig, ax)`. Example call in the codebase: diff --git a/docs/components/structural_modeling/Manual_structural_modeling.md b/docs/components/structural_modeling/Manual_structural_modeling.md index d5de3207..0a323979 100644 --- a/docs/components/structural_modeling/Manual_structural_modeling.md +++ b/docs/components/structural_modeling/Manual_structural_modeling.md @@ -335,11 +335,25 @@ plot_structural_model_3D(structural_model_result.structural_frame, mesh_type="ma - **`show_input_data`** *(optional)*: Overlay input surface points and orientation arrows. Default `True`. - **`show_grid`** *(optional)*: Outline the grid cells the slice cuts — uniform voxels on a Regular Grid, cells of different sizes on an Octree Grid. Default `False`. - **`title_suffix`** *(optional)*: Text appended to the plot title. Default `""`. +- **`ax`** *(optional, Python only)*: Matplotlib axes to draw into, e.g. one subplot of a larger figure, instead of a new figure. You then arrange and show the figure yourself. Default `None`. +- **`show`** *(optional, Python only)*: Show the figure. Set `False` to add to the plot first. Default `True`. -The Workbench version exposes `axis` (a choice of x, y or z), `index` (empty = the mid-point) and `show_grid`; the other options keep their defaults. +The function returns the figure and the axes, `(fig, ax)`. The Workbench version exposes `axis` (a choice of x, y or z), `index` (empty = the mid-point) and `show_grid`; the other options keep their defaults. ```python plot_structural_model_2D(structural_model_result.structural_frame, axis="x", index=20) + +# Draw the section on top of an outcrop photo (image extent in model coordinates) +fig, ax = plot_structural_model_2D(structural_model_result.structural_frame, show=False) +ax.imshow(outcrop_image, extent=[0, 50, 0, 35], alpha=0.5) +plt.show() + +# Compare two models side by side +fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 5)) +plot_structural_model_2D(result_rbf.structural_frame, ax=ax1, show=False) +plot_structural_model_2D(result_kriging.structural_frame, ax=ax2, show=False) +plt.tight_layout() +plt.show() ``` ### Inspect the fault model @@ -383,6 +397,7 @@ plot_fault_model_3D(fault_model_result.fault_frame, show_domain_map=True, domain - **`show_input_data`** *(optional)*: Plot input surface points, if available. Default `True`. - **`show_fault_contours`** *(optional)*: Overlay fault isolines. Default `True`. - **`show_grid`** *(optional)*: Outline the grid cells the slice cuts, as in `plot_structural_model_2D`. Default `False`. +- **`ax`**, **`show`** *(optional, Python only)*: As in `plot_structural_model_2D`; the function returns `(fig, ax)`. The Workbench version exposes `axis` (a choice of x, y or z), `index` (empty = the mid-point) and `show_grid`, as in `Plot Model Result 2D`. diff --git a/tests/tests_simulation_components/test_simulation_visualization.py b/tests/tests_simulation_components/test_simulation_visualization.py index 68f57ba6..4fdc6d2f 100644 --- a/tests/tests_simulation_components/test_simulation_visualization.py +++ b/tests/tests_simulation_components/test_simulation_visualization.py @@ -222,3 +222,39 @@ def test_line_cells_returns_only_the_1d_elements(): assert int(lines.celltypes[0]) == pv.CellType.LINE assert _line_cells(build_grid_from_class(_hex_sim(times=(0.0,)), 0.0)) is None assert _line_cells(pv.PolyData(points)) is None + + +def test_2d_simulation_plots_draw_into_given_axes_and_return_them(monkeypatch): + """ax= / axes= put the plots into the caller's figure; show=False leaves it unshown; each returns its axes.""" + import matplotlib + import matplotlib.pyplot as plt + from core.simulation_components.simulation_visualization import simulation_visualization as sv + + backend = matplotlib.get_backend() + plt.switch_backend("Agg") + shown = [] + monkeypatch.setattr(plt, "show", lambda *args, **kwargs: shown.append(True)) + try: + sim = _hex_sim() + fig, axes = plt.subplots(2, 3) + a = axes.flat + + assert sv.plot_cross_section_2D(sim, "T", origin=(0, 1.5, 0), axes=[a[0], a[1]], show=False, + resolution=11) == (fig, [a[0], a[1]]) + assert sv.plot_cross_section_difference_2D(sim, "T", origin=(0, 1.5, 0), normal=(0, 1, 0), ax=a[2], + show=False, resolution=11) == (fig, a[2]) + assert sv.plot_variable_along_line(sim, "T", 1.0, (0, 1.5, 1), (4, 1.5, 1), n_samples=10, ax=a[3], + show=False) == (fig, a[3]) + assert sv.plot_variable_time_series(sim, "T", (1, 1.5, 1), ax=a[4], show=False) == (fig, a[4]) + + assert plt.get_fignums() == [fig.number] # nothing drew into a figure of its own + assert a[0].collections and a[2].collections and a[3].lines and a[4].lines + assert not shown + with pytest.raises(ValueError, match="two axes"): + sv.plot_cross_section_2D(sim, "T", origin=(0, 1.5, 0), axes=[a[5]], show=False, resolution=11) + + fig_line, ax_line = sv.plot_variable_along_line(sim, "T", 1.0, (0, 1.5, 1), (4, 1.5, 1), n_samples=10) + assert fig_line is not fig and fig_line.axes == [ax_line] and shown == [True] # own figure, shown by default + finally: + plt.close("all") + plt.switch_backend(backend) diff --git a/tests/tests_structural_modeling_components/test_visualization_2d.py b/tests/tests_structural_modeling_components/test_visualization_2d.py index 754c305b..ba208dae 100644 --- a/tests/tests_structural_modeling_components/test_visualization_2d.py +++ b/tests/tests_structural_modeling_components/test_visualization_2d.py @@ -138,3 +138,33 @@ def test_show_grid_before_computing_warns_and_plots_without_outlines(uncomputed) plot(f, show_grid=True) assert all(not _outlines(ax) for ax in plt.gcf().axes) plt.close("all") + + +def test_2d_plots_draw_into_given_axes_and_return_them(results, monkeypatch): + """ax= puts a section into a subplot of the caller's figure; show=False leaves it unshown for more drawing.""" + shown = [] + monkeypatch.setattr(plt, "show", lambda *args, **kwargs: shown.append(True)) + frame = results["regular"] + fig, (ax_model, ax_faults) = plt.subplots(1, 2) + + returned = viz.plot_structural_model_2D(frame, ax=ax_model, show=False) + assert returned == (fig, ax_model) + returned = viz.plot_fault_model_2D(frame.fault_frame, ax=ax_faults, show=False) + assert returned == (fig, ax_faults) + + assert plt.get_fignums() == [fig.number] # no figure of their own + assert ax_model.images and ax_faults.images + assert not shown + + +def test_2d_plots_return_their_own_figure_for_additions(results, monkeypatch): + """Without ax the plot makes and returns its own figure; show=False lets the caller add e.g. an image.""" + shown = [] + monkeypatch.setattr(plt, "show", lambda *args, **kwargs: shown.append(True)) + fig, ax = viz.plot_structural_model_2D(results["regular"], show=False) + assert fig.axes[0] is ax and not shown + ax.imshow(np.zeros((2, 2)), extent=ax.get_xlim() + ax.get_ylim(), alpha=0.5) + assert len(ax.images) == 2 + + viz.plot_structural_model_2D(results["regular"]) + assert shown == [True] # shown by default, as before