Skip to content

Commit b25e081

Browse files
feat: Add Plotly as backend
1 parent 23dc422 commit b25e081

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

pyproject.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ pyvistaqt = [
3636
"pyside6 >= 6.8.0,<7",
3737
"pyvistaqt >= 0.11.1,<1",
3838
]
39+
40+
plotly = [
41+
"plotly >= 5.15.0,<6",
42+
]
3943
tests = [
4044
"pytest==8.4.2",
4145
"pyvista==0.46.3",
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""Plotly backend interface for visualization."""
2+
from ansys.tools.visualization_interface.backends._base import BaseBackend
3+
from ansys.tools.visualization_interface.types.mesh_object_plot import MeshObjectPlot
4+
import plotly.graph_objects as go
5+
from pyvista import PolyData
6+
from typing import Union, Iterable, Any
7+
8+
9+
class PlotlyInterface(BaseBackend):
10+
"""Plotly interface for visualization."""
11+
12+
def __init__(self, **kwargs):
13+
self._fig = go.Figure()
14+
15+
def _pv_to_mesh3d(self, pv_mesh: PolyData) -> go.Mesh3d:
16+
"""Convert a PyVista PolyData mesh to Plotly Mesh3d format."""
17+
points = pv_mesh.points
18+
x, y, z = points[:, 0], points[:, 1], points[:, 2]
19+
20+
faces = pv_mesh.faces.reshape((-1, 4)) # First number in each row is the number of points in the face (3 for triangles)
21+
i, j, k = faces[:, 1], faces[:, 2], faces[:, 3]
22+
23+
return go.Mesh3d(x=x, y=y, z=z, i=i, j=j, k=k)
24+
@property
25+
def layout(self) -> Any:
26+
"""Get the current layout of the Plotly figure."""
27+
return self._fig.layout
28+
29+
@setters.layout
30+
def layout(self, new_layout: Any):
31+
"""Set a new layout for the Plotly figure."""
32+
self._fig.update_layout(new_layout)
33+
34+
def plot_iter(self, plotting_list):
35+
"""Plot multiple objects using Plotly."""
36+
for item in plotting_list:
37+
self.plot(item)
38+
39+
40+
def plot(self, plottable_object: Union[PolyData, MeshObjectPlot, go.Mesh3d], **plotting_options):
41+
"""Plot a single object using Plotly."""
42+
if isinstance(plottable_object, PolyData):
43+
mesh = self._pv_to_mesh3d(plottable_object)
44+
self._fig.add_trace(mesh)
45+
elif isinstance(plottable_object, MeshObjectPlot):
46+
pv_mesh = plottable_object.mesh
47+
mesh = self._pv_to_mesh3d(pv_mesh)
48+
self._fig.add_trace(mesh)
49+
elif isinstance(plottable_object, go.Mesh3d):
50+
self._fig.add_trace(plottable_object)
51+
else:
52+
try:
53+
self._fig.add_trace(plottable_object)
54+
except Exception:
55+
raise TypeError("Unsupported plottable_object type for PlotlyInterface.")
56+
57+
def show(self):
58+
"""Render the Plotly scene."""
59+
self._fig.show()

0 commit comments

Comments
 (0)