iplotx 0.9.0__py3-none-any.whl → 0.10.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
iplotx/art3d/edge.py ADDED
@@ -0,0 +1,65 @@
1
+ """
2
+ Module containing code to manipulate edge visualisations in 3D, especially the Edge3DCollection class.
3
+ """
4
+
5
+ from mpl_toolkits.mplot3d.art3d import (
6
+ Line3DCollection,
7
+ )
8
+
9
+ from ..utils.matplotlib import (
10
+ _forwarder,
11
+ )
12
+ from ..edge import (
13
+ EdgeCollection,
14
+ )
15
+
16
+
17
+ @_forwarder(
18
+ (
19
+ "set_clip_path",
20
+ "set_clip_box",
21
+ "set_snap",
22
+ "set_sketch_params",
23
+ "set_animated",
24
+ "set_picker",
25
+ )
26
+ )
27
+ class Edge3DCollection(Line3DCollection):
28
+ """Collection of vertex patches for plotting."""
29
+
30
+ pass
31
+
32
+
33
+ def edge_collection_2d_to_3d(
34
+ col: EdgeCollection,
35
+ zdir: str = "z",
36
+ depthshade: bool = True,
37
+ axlim_clip: bool = False,
38
+ ):
39
+ """Convert a 2D EdgeCollection to a 3D Edge3DCollection.
40
+
41
+ Parameters:
42
+ col: The 2D EdgeCollection to convert.
43
+ zs: The z coordinate(s) to use for the 3D vertices.
44
+ zdir: The axis to use as the z axis (default is "z").
45
+ depthshade: Whether to apply depth shading (default is True).
46
+ axlim_clip: Whether to clip the vertices to the axes limits (default is False).
47
+ """
48
+ if not isinstance(col, EdgeCollection):
49
+ raise TypeError("vertices must be a VertexCollection")
50
+
51
+ # TODO: if we make Edge3DCollection a dynamic drawer, this will need to change
52
+ # fundamentally. Also, this currently does not handle labels properly.
53
+ vinfo = col._get_adjacent_vertices_info()
54
+
55
+ segments3d = []
56
+ for offset1, offset2 in vinfo["offsets"]:
57
+ segment = [tuple(offset1), tuple(offset2)]
58
+ segments3d.append(segment)
59
+
60
+ # NOTE: after this line, none of the EdgeCollection methods will work
61
+ # It's become a static drawer now
62
+ col.__class__ = Edge3DCollection
63
+
64
+ col.set_segments(segments3d)
65
+ col._axlim_clip = axlim_clip
iplotx/art3d/vertex.py ADDED
@@ -0,0 +1,69 @@
1
+ """
2
+ Module containing code to manipulate vertex visualisations in 3D, especially the Vertex3DCollection class.
3
+ """
4
+
5
+ from typing import (
6
+ Sequence,
7
+ )
8
+ import numpy as np
9
+ from matplotlib import (
10
+ cbook,
11
+ )
12
+ from mpl_toolkits.mplot3d.art3d import Path3DCollection
13
+
14
+ from ..utils.matplotlib import (
15
+ _forwarder,
16
+ )
17
+ from ..vertex import (
18
+ VertexCollection,
19
+ )
20
+
21
+
22
+ @_forwarder(
23
+ (
24
+ "set_clip_path",
25
+ "set_clip_box",
26
+ "set_snap",
27
+ "set_sketch_params",
28
+ "set_animated",
29
+ "set_picker",
30
+ )
31
+ )
32
+ class Vertex3DCollection(VertexCollection, Path3DCollection):
33
+ """Collection of vertex patches for plotting."""
34
+
35
+ def draw(self, renderer) -> None:
36
+ """Draw the collection of vertices in 3D.
37
+
38
+ Parameters:
39
+ renderer: The renderer to use for drawing.
40
+ """
41
+ with self._use_zordered_offset():
42
+ with cbook._setattr_cm(self, _in_draw=True):
43
+ VertexCollection.draw(self, renderer)
44
+
45
+
46
+ def vertex_collection_2d_to_3d(
47
+ col: VertexCollection,
48
+ zs: np.ndarray | float | Sequence[float] = 0,
49
+ zdir: str = "z",
50
+ depthshade: bool = True,
51
+ axlim_clip: bool = False,
52
+ ):
53
+ """Convert a 2D VertexCollection to a 3D Vertex3DCollection.
54
+
55
+ Parameters:
56
+ col: The 2D VertexCollection to convert.
57
+ zs: The z coordinate(s) to use for the 3D vertices.
58
+ zdir: The axis to use as the z axis (default is "z").
59
+ depthshade: Whether to apply depth shading (default is True).
60
+ axlim_clip: Whether to clip the vertices to the axes limits (default is False).
61
+ """
62
+ if not isinstance(col, VertexCollection):
63
+ raise TypeError("vertices must be a VertexCollection")
64
+
65
+ col.__class__ = Vertex3DCollection
66
+ col._offset_zordered = None
67
+ col._depthshade = depthshade
68
+ col._in_draw = False
69
+ col.set_3d_properties(zs, zdir, axlim_clip)
iplotx/artists.py CHANGED
@@ -10,6 +10,8 @@ from .label import LabelCollection
10
10
  from .edge.arrow import EdgeArrowCollection
11
11
  from .edge.leaf import LeafEdgeCollection
12
12
  from .cascades import CascadeCollection
13
+ from .art3d.vertex import Vertex3DCollection
14
+ from .art3d.edge import Edge3DCollection
13
15
 
14
16
 
15
17
  ___all__ = (
@@ -21,4 +23,6 @@ ___all__ = (
21
23
  LabelCollection,
22
24
  EdgeArrowCollection,
23
25
  CascadeCollection,
26
+ Vertex3DCollection,
27
+ Edge3DCollection,
24
28
  )
iplotx/edge/__init__.py CHANGED
@@ -193,6 +193,16 @@ class EdgeCollection(mpl.collections.PatchCollection):
193
193
  self._update_arrows()
194
194
  self._update_labels()
195
195
 
196
+ def set_transform(self, transform: mpl.transforms.Transform) -> None:
197
+ """Set the transform for the edges and their children."""
198
+ super().set_transform(transform)
199
+ if hasattr(self, "_subedges"):
200
+ self._subedges.set_transform(transform)
201
+ if hasattr(self, "_arrows"):
202
+ self._arrows.set_offset_transform(transform)
203
+ if hasattr(self, "_label_collection"):
204
+ self._label_collection.set_transform(transform)
205
+
196
206
  @property
197
207
  def directed(self) -> bool:
198
208
  """Whether the network is directed."""
iplotx/edge/geometry.py CHANGED
@@ -1,5 +1,7 @@
1
1
  """
2
2
  Support module with geometry- and path-related functions for edges.
3
+
4
+ 3D geometry is in its separate module :mod:`.geometry3d`.
3
5
  """
4
6
 
5
7
  from typing import (
@@ -14,6 +16,7 @@ from ..typing import (
14
16
  Pair,
15
17
  )
16
18
  from .ports import _get_port_unit_vector
19
+ from .geometry3d import _compute_edge_path_3d
17
20
 
18
21
 
19
22
  def _compute_loops_per_angle(nloops, angles):
@@ -65,6 +68,14 @@ def _compute_loops_per_angle(nloops, angles):
65
68
 
66
69
 
67
70
  def _get_shorter_edge_coords(vpath, vsize, theta, shrink=0):
71
+ """Get the coordinates of an edge tip such that it touches the vertex border.
72
+
73
+ Parameters:
74
+ vpath: The vertex path, in figure coordinates (so scaled by dpi).
75
+ vsize: The vertex max size, in figure coordinates (so scaled by dpi).
76
+ theta: The angle of the edge inpinging into the vertex, in radians, in figure coordinates.
77
+ shrink: Additional shrinking of the edge, in figure coordinates (so scaled by dpi).
78
+ """
68
79
  # Bound theta from -pi to pi (why is that not guaranteed?)
69
80
  theta = (theta + pi) % (2 * pi) - pi
70
81
 
@@ -468,7 +479,7 @@ def _compute_edge_path_curved(
468
479
  return path, tuple(thetas)
469
480
 
470
481
 
471
- def _compute_edge_path(
482
+ def _compute_edge_path_2d(
472
483
  *args,
473
484
  tension: float = 0,
474
485
  waypoints: str | tuple[float, float] | Sequence[tuple[float, float]] | np.ndarray = "none",
@@ -502,3 +513,25 @@ def _compute_edge_path(
502
513
  ports=ports,
503
514
  **kwargs,
504
515
  )
516
+
517
+
518
+ def _compute_edge_path(
519
+ vcoord_data,
520
+ *args,
521
+ **kwargs,
522
+ ):
523
+ """Compute the edge path in either 2D or 3D.
524
+
525
+ Parameters:
526
+ vcoord_data: The vertex coordinates in data coordinates. This is used to
527
+ determine the dimensionality of the layout.
528
+ *args: Additional arguments passed to the internal functions.
529
+ **kwargs: Additional keyword arguments passed to the internal functions.
530
+
531
+ Returns:
532
+ The computed edge path and the angles at the start and end of the edge.
533
+ """
534
+ ndim = len(vcoord_data[0])
535
+ if ndim == 2:
536
+ return _compute_edge_path_2d(vcoord_data, *args, **kwargs)
537
+ return _compute_edge_path_3d(vcoord_data, *args, **kwargs)
@@ -0,0 +1,113 @@
1
+ """
2
+ Support for computing edge paths in 3D.
3
+ """
4
+
5
+ from typing import (
6
+ Optional,
7
+ Sequence,
8
+ )
9
+ import numpy as np
10
+ import matplotlib as mpl
11
+
12
+ from ..typing import (
13
+ Pair,
14
+ )
15
+
16
+
17
+ def _compute_edge_path_straight(
18
+ vcoord_data,
19
+ vpath_fig,
20
+ vsize_fig,
21
+ trans,
22
+ trans_inv,
23
+ layout_coordinate_system: str = "cartesian",
24
+ shrink: float = 0,
25
+ **kwargs,
26
+ ):
27
+ """Compute straight edge path between two vertices, in 3D.
28
+
29
+ Parameters:
30
+ vcoord_data: Vertex coordinates in data coordinates, shape (2, 3).
31
+ vpath_fig: Vertex path in figure coordinates.
32
+ vsize_fig: Vertex size in figure coordinates.
33
+ trans: Transformation from data to figure coordinates.
34
+ trans_inv: Inverse transformation from figure to data coordinates.
35
+ layout_coordinate_system: The coordinate system of the layout.
36
+ shrink: Amount to shorten the edge at each end, in figure coordinates.
37
+ **kwargs: Additional keyword arguments (not used).
38
+ Returns:
39
+ A pair with the path and a tuple of angles of exit and entry, in radians.
40
+
41
+ """
42
+
43
+ if layout_coordinate_system not in ("cartesian"):
44
+ raise ValueError(
45
+ f"Layout coordinate system not supported for straight edges in 3D: {layout_coordinate_system}.",
46
+ )
47
+
48
+ vcoord_data_cart = vcoord_data
49
+
50
+ # Coordinates in figure (default) coords
51
+ vcoord_fig = trans(vcoord_data_cart)
52
+
53
+ points = []
54
+
55
+ # Angles of the straight line
56
+ # FIXME: In 2D, this is only used to make space for loops
57
+ # let's ignore for now
58
+ # theta = atan2(*((vcoord_fig[1] - vcoord_fig[0])[::-1]))
59
+ theta = 0
60
+
61
+ # TODO: Shorten at starting vertex (?)
62
+ vs = vcoord_fig[0]
63
+ points.append(vs)
64
+
65
+ # TODO: Shorten at end vertex (?)
66
+ ve = vcoord_fig[1]
67
+ points.append(ve)
68
+
69
+ codes = ["MOVETO", "LINETO"]
70
+ path = mpl.path.Path(
71
+ points,
72
+ codes=[getattr(mpl.path.Path, x) for x in codes],
73
+ )
74
+ path.vertices = trans_inv(path.vertices)
75
+ return path, (theta, theta + np.pi)
76
+
77
+
78
+ def _compute_edge_path_3d(
79
+ *args,
80
+ tension: float = 0,
81
+ waypoints: str | tuple[float, float] | Sequence[tuple[float, float]] | np.ndarray = "none",
82
+ ports: Pair[Optional[str]] = (None, None),
83
+ layout_coordinate_system: str = "cartesian",
84
+ **kwargs,
85
+ ):
86
+ """Compute the edge path in a few different ways."""
87
+ if (waypoints != "none") and (tension != 0):
88
+ raise ValueError("Waypoints not supported for curved edges.")
89
+
90
+ if waypoints != "none":
91
+ raise NotImplementedError("Waypoints not implemented for 3D edges.")
92
+ # return _compute_edge_path_waypoints(
93
+ # waypoints,
94
+ # *args,
95
+ # layout_coordinate_system=layout_coordinate_system,
96
+ # ports=ports,
97
+ # **kwargs,
98
+ # )
99
+
100
+ if np.isscalar(tension) and (tension == 0):
101
+ return _compute_edge_path_straight(
102
+ *args,
103
+ layout_coordinate_system=layout_coordinate_system,
104
+ **kwargs,
105
+ )
106
+
107
+ raise NotImplementedError("Curved edges not implemented for 3D edges.")
108
+ # return _compute_edge_path_curved(
109
+ # tension,
110
+ # *args,
111
+ # ports=ports,
112
+ # **kwargs,
113
+ # )
iplotx/groups.py CHANGED
@@ -4,6 +4,7 @@ Module for vertex groupings code, especially the GroupingArtist class.
4
4
 
5
5
  from typing import Union
6
6
  import numpy as np
7
+ import pandas as pd
7
8
  import matplotlib as mpl
8
9
  from matplotlib.collections import PatchCollection
9
10
 
@@ -64,6 +65,9 @@ class GroupingArtist(PatchCollection):
64
65
  self._points_per_curve = points_per_curve
65
66
 
66
67
  network = kwargs.pop("network", None)
68
+ self.layout = normalise_layout(layout, network=network)
69
+ self.ndim = layout.shape[1]
70
+
67
71
  patches, grouping, coords_hulls = self._create_patches(
68
72
  grouping,
69
73
  layout,
@@ -89,6 +93,21 @@ class GroupingArtist(PatchCollection):
89
93
  self._compute_paths(self.get_figure(root=True).dpi)
90
94
  return ret
91
95
 
96
+ @property
97
+ def axes(self):
98
+ return PatchCollection.axes.__get__(self)
99
+
100
+ @axes.setter
101
+ def axes(self, new_axes):
102
+ PatchCollection.axes.__set__(self, new_axes)
103
+ for child in self.get_children():
104
+ child.axes = new_axes
105
+ self.set_figure(new_axes.figure)
106
+
107
+ def get_layout(self) -> pd.DataFrame:
108
+ """Get the layout used for this grouping."""
109
+ return self.layout
110
+
92
111
  def get_vertexpadding(self) -> float:
93
112
  """Get the vertex padding of each group."""
94
113
  return self._vertexpadding
@@ -98,7 +117,6 @@ class GroupingArtist(PatchCollection):
98
117
  return self.get_vertexpadding() * dpi / 72.0 * self._factor
99
118
 
100
119
  def _create_patches(self, grouping, layout, network, **kwargs):
101
- layout = normalise_layout(layout, network=network)
102
120
  grouping = normalise_grouping(grouping, layout)
103
121
  style = get_style(".grouping")
104
122
  style.pop("vertexpadding", None)
@@ -30,23 +30,22 @@ class IGraphDataProvider(NetworkDataProvider):
30
30
  edge_labels: Optional[Sequence[str] | dict[str]] = None,
31
31
  ) -> NetworkData:
32
32
  """Create network data object for iplotx from an igraph object."""
33
- network = self.network
34
- directed = self.is_directed()
35
33
 
36
- # Recast vertex_labels=False as vertex_labels=None
37
- if np.isscalar(vertex_labels) and (not vertex_labels):
38
- vertex_labels = None
39
-
40
- # Vertices are ordered integers, no gaps
34
+ # Get layout
41
35
  vertex_df = normalise_layout(
42
36
  layout,
43
- network=network,
37
+ network=self.network,
44
38
  nvertices=self.number_of_vertices(),
45
39
  )
46
40
  ndim = vertex_df.shape[1]
47
41
  vertex_df.columns = _make_layout_columns(ndim)
48
42
 
43
+ # Vertices are ordered integers, no gaps
44
+
49
45
  # Vertex labels
46
+ # Recast vertex_labels=False as vertex_labels=None
47
+ if np.isscalar(vertex_labels) and (not vertex_labels):
48
+ vertex_labels = None
50
49
  if vertex_labels is not None:
51
50
  if np.isscalar(vertex_labels):
52
51
  vertex_df["label"] = vertex_df.index.astype(str)
@@ -57,7 +56,7 @@ class IGraphDataProvider(NetworkDataProvider):
57
56
 
58
57
  # Edges are a list of tuples, because of multiedges
59
58
  tmp = []
60
- for edge in network.es:
59
+ for edge in self.network.es:
61
60
  row = {"_ipx_source": edge.source, "_ipx_target": edge.target}
62
61
  row.update(edge.attributes())
63
62
  tmp.append(row)
@@ -76,7 +75,7 @@ class IGraphDataProvider(NetworkDataProvider):
76
75
  network_data = {
77
76
  "vertex_df": vertex_df,
78
77
  "edge_df": edge_df,
79
- "directed": directed,
78
+ "directed": self.is_directed(),
80
79
  "ndim": ndim,
81
80
  }
82
81
  return network_data
@@ -33,25 +33,20 @@ class NetworkXDataProvider(NetworkDataProvider):
33
33
 
34
34
  import networkx as nx
35
35
 
36
- network = self.network
37
-
38
- directed = self.is_directed()
39
-
40
- # Recast vertex_labels=False as vertex_labels=None
41
- if np.isscalar(vertex_labels) and (not vertex_labels):
42
- vertex_labels = None
43
-
44
- # Vertices are indexed by node ID
36
+ # Get layout
45
37
  vertex_df = normalise_layout(
46
38
  layout,
47
- network=network,
39
+ network=self.network,
48
40
  nvertices=self.number_of_vertices(),
49
- ).loc[pd.Index(network.nodes)]
41
+ )
50
42
  ndim = vertex_df.shape[1]
51
43
  vertex_df.columns = _make_layout_columns(ndim)
52
44
 
45
+ # Vertices are indexed by node ID
46
+ vertex_df = vertex_df.loc[pd.Index(self.network.nodes)]
47
+
53
48
  # Vertex internal properties
54
- tmp = pd.DataFrame(dict(network.nodes.data())).T
49
+ tmp = pd.DataFrame(dict(self.network.nodes.data())).T
55
50
  # Arrays become a single column, which we have already anyway
56
51
  if isinstance(layout, str) and (layout in tmp.columns):
57
52
  del tmp[layout]
@@ -60,6 +55,9 @@ class NetworkXDataProvider(NetworkDataProvider):
60
55
  del tmp
61
56
 
62
57
  # Vertex labels
58
+ # Recast vertex_labels=False as vertex_labels=None
59
+ if np.isscalar(vertex_labels) and (not vertex_labels):
60
+ vertex_labels = None
63
61
  if vertex_labels is None:
64
62
  if "label" in vertex_df:
65
63
  del vertex_df["label"]
@@ -78,7 +76,7 @@ class NetworkXDataProvider(NetworkDataProvider):
78
76
 
79
77
  # Edges are a list of tuples, because of multiedges
80
78
  tmp = []
81
- for u, v, d in network.edges.data():
79
+ for u, v, d in self.network.edges.data():
82
80
  row = {"_ipx_source": u, "_ipx_target": v}
83
81
  row.update(d)
84
82
  tmp.append(row)
@@ -112,7 +110,7 @@ class NetworkXDataProvider(NetworkDataProvider):
112
110
  network_data = {
113
111
  "vertex_df": vertex_df,
114
112
  "edge_df": edge_df,
115
- "directed": directed,
113
+ "directed": self.is_directed(),
116
114
  "ndim": ndim,
117
115
  }
118
116
  return network_data
iplotx/label.py CHANGED
@@ -77,6 +77,17 @@ class LabelCollection(mpl.artist.Artist):
77
77
  child.set_figure(fig)
78
78
  self._update_offsets(dpi=fig.dpi)
79
79
 
80
+ def set_transform(self, transform: mpl.transforms.Transform) -> None:
81
+ """Set the transform for this artist and children.
82
+
83
+ Parameters:
84
+ transform: The transform to set.
85
+ """
86
+ super().set_transform(transform)
87
+ if hasattr(self, "_labelartists"):
88
+ for art in self._labelartists:
89
+ art.set_transform(transform)
90
+
80
91
  def get_texts(self):
81
92
  """Get the texts of the labels."""
82
93
  return [child.get_text() for child in self.get_children()]
iplotx/network.py CHANGED
@@ -30,6 +30,13 @@ from .edge import (
30
30
  EdgeCollection,
31
31
  make_stub_patch as make_undirected_edge_patch,
32
32
  )
33
+ from .art3d.vertex import (
34
+ vertex_collection_2d_to_3d,
35
+ )
36
+ from .art3d.edge import (
37
+ Edge3DCollection,
38
+ edge_collection_2d_to_3d,
39
+ )
33
40
 
34
41
 
35
42
  @_forwarder(
@@ -63,6 +70,10 @@ class NetworkArtist(mpl.artist.Artist):
63
70
  will be drawn. If a list, the labels are taken from the list. If a dict, the keys
64
71
  should be the vertex IDs and the values should be the labels.
65
72
  edge_labels: The labels for the edges. If None, no edge labels will be drawn.
73
+ transform: The transform to use for the vertices. Default is IdentityTransform.
74
+ offset_transform: The transform to use as offset transform for the vertices and main
75
+ transform for the edges. Default is None, but this should eventually be set to
76
+ ax.transData once the artist is added to an Axes.
66
77
 
67
78
  """
68
79
  self.network = network
@@ -111,7 +122,7 @@ class NetworkArtist(mpl.artist.Artist):
111
122
  @classmethod
112
123
  def from_edgecollection(
113
124
  cls: "NetworkArtist", # NOTE: This is fixed in Python 3.14
114
- edge_collection: EdgeCollection,
125
+ edge_collection: EdgeCollection | Edge3DCollection,
115
126
  ) -> Self:
116
127
  """Create a NetworkArtist from iplotx artists.
117
128
 
@@ -125,7 +136,7 @@ class NetworkArtist(mpl.artist.Artist):
125
136
  vertex_collection = edge_collection._vertex_collection
126
137
  layout = vertex_collection._layout
127
138
  transform = vertex_collection.get_transform()
128
- offset_transform = edge_collection.get_transform()
139
+ offset_transform = vertex_collection.get_offset_transform()
129
140
 
130
141
  # Follow the steps in the normal constructor
131
142
  self = cls(
@@ -134,6 +145,7 @@ class NetworkArtist(mpl.artist.Artist):
134
145
  transform=transform,
135
146
  offset_transform=offset_transform,
136
147
  )
148
+ # TODO: should we make copies here?
137
149
  self._vertices = vertex_collection
138
150
  self._edges = edge_collection
139
151
 
@@ -150,6 +162,17 @@ class NetworkArtist(mpl.artist.Artist):
150
162
  for child in self.get_children():
151
163
  child.set_figure(fig)
152
164
 
165
+ @property
166
+ def axes(self):
167
+ return mpl.artist.Artist.axes.__get__(self)
168
+
169
+ @axes.setter
170
+ def axes(self, new_axes):
171
+ mpl.artist.Artist.axes.__set__(self, new_axes)
172
+ for child in self.get_children():
173
+ child.axes = new_axes
174
+ self.set_figure(new_axes.figure)
175
+
153
176
  def get_offset_transform(self):
154
177
  """Get the offset transform (for vertices/edges)."""
155
178
  return self._offset_transform
@@ -157,6 +180,10 @@ class NetworkArtist(mpl.artist.Artist):
157
180
  def set_offset_transform(self, offset_transform):
158
181
  """Set the offset transform (for vertices/edges)."""
159
182
  self._offset_transform = offset_transform
183
+ if hasattr(self, "_vertices"):
184
+ self._vertices.set_offset_transform(offset_transform)
185
+ if hasattr(self, "_edges"):
186
+ self._edges.set_transform(offset_transform)
160
187
 
161
188
  def get_vertices(self):
162
189
  """Get VertexCollection artist."""
@@ -210,10 +237,23 @@ class NetworkArtist(mpl.artist.Artist):
210
237
  self.axes.autoscale_view(tight=tight)
211
238
 
212
239
  def get_layout(self):
213
- layout_columns = [f"_ipx_layout_{i}" for i in range(self._ipx_internal_data["ndim"])]
240
+ """Get the vertex layout.
241
+
242
+ Returns:
243
+ The vertex layout as a DataFrame.
244
+ """
245
+ layout_columns = [f"_ipx_layout_{i}" for i in range(self.get_ndim())]
214
246
  vertex_layout_df = self._ipx_internal_data["vertex_df"][layout_columns]
215
247
  return vertex_layout_df
216
248
 
249
+ def get_ndim(self):
250
+ """Get the dimensionality of the layout.
251
+
252
+ Returns:
253
+ The dimensionality of the layout (2 or 3).
254
+ """
255
+ return self._ipx_internal_data["ndim"]
256
+
217
257
  def _get_label_series(self, kind):
218
258
  # Equivalence vertex/node
219
259
  if kind == "node":
@@ -238,6 +278,13 @@ class NetworkArtist(mpl.artist.Artist):
238
278
  offset_transform=self.get_offset_transform(),
239
279
  )
240
280
 
281
+ if self.get_ndim() == 3:
282
+ vertex_collection_2d_to_3d(
283
+ self._vertices,
284
+ zs=self.get_layout().iloc[:, 2].values,
285
+ depthshade=False,
286
+ )
287
+
241
288
  def _add_edges(self):
242
289
  """Add edges to the network artist.
243
290
 
@@ -319,6 +366,11 @@ class NetworkArtist(mpl.artist.Artist):
319
366
  if "cmap" in edge_style:
320
367
  self._edges.set_array(colorarray)
321
368
 
369
+ if self.get_ndim() == 3:
370
+ edge_collection_2d_to_3d(
371
+ self._edges,
372
+ )
373
+
322
374
  @_stale_wrapper
323
375
  def draw(self, renderer):
324
376
  """Draw each of the children, with some buffering mechanism."""
@@ -333,6 +385,8 @@ class NetworkArtist(mpl.artist.Artist):
333
385
  children = list(self.get_children())
334
386
  children.sort(key=lambda x: x.zorder)
335
387
  for art in children:
388
+ if (self.get_ndim() == 3) and (art.axes is not None):
389
+ art.do_3d_projection()
336
390
  art.draw(renderer)
337
391
 
338
392
 
iplotx/plotting.py CHANGED
@@ -3,6 +3,7 @@ from contextlib import nullcontext
3
3
  import numpy as np
4
4
  import pandas as pd
5
5
  import matplotlib as mpl
6
+ from mpl_toolkits.mplot3d.axes3d import Axes3D
6
7
  import matplotlib.pyplot as plt
7
8
 
8
9
  from .typing import (
@@ -28,7 +29,7 @@ def network(
28
29
  style: str | dict | Sequence[str | dict] = (),
29
30
  title: Optional[str] = None,
30
31
  aspect: Optional[str | float] = None,
31
- margins: float | tuple[float, float] = 0,
32
+ margins: float | tuple[float, float] | tuple[float, float, float] = 0,
32
33
  strip_axes: bool = True,
33
34
  figsize: Optional[tuple[float, float]] = None,
34
35
  **kwargs,
@@ -53,13 +54,15 @@ def network(
53
54
  style: Apply this style for the objects to plot. This can be a sequence (e.g. list)
54
55
  of styles and they will be applied in order.
55
56
  title: If not None, set the axes title to this value.
56
- aspect: If not None, set the aspect ratio of the axis to this value. The most common
57
- value is 1.0, which proportionates x- and y-axes.
57
+ aspect: If not None, set the aspect ratio of the axis to this value. In 2D, the most
58
+ common value is 1.0, which proportionates x- and y-axes. In 3D, only string
59
+ values are accepted (see the documentation of Axes.set_aspect).
58
60
  margins: How much margin to leave around the plot. A higher value (e.g. 0.1) can be
59
61
  used as a quick fix when some vertex shapes reach beyond the plot edge. This is
60
62
  a fraction of the data limits, so 0.1 means 10% of the data limits will be left
61
- as margin.
62
- strip_axes: If True, remove axis spines and ticks.
63
+ as margin. A pair (in 2D) or triplet (in 3D) of floats can also be provided and
64
+ applied to each axis separately.
65
+ strip_axes: If True, remove axis spines and ticks. In 3D, only ticks are removed.
63
66
  figsize: If ax is None, a new matplotlib Figure is created. This argument specifies
64
67
  the (width, height) dimension of the figure in inches. If ax is not None, this
65
68
  argument is ignored. If None, the default matplotlib figure size is used.
@@ -83,9 +86,6 @@ def network(
83
86
  if (network is None) and (grouping is None):
84
87
  raise ValueError("At least one of network or grouping must be provided.")
85
88
 
86
- if ax is None:
87
- fig, ax = plt.subplots(figsize=figsize)
88
-
89
89
  artists = []
90
90
  if network is not None:
91
91
  nwkart = NetworkArtist(
@@ -94,30 +94,58 @@ def network(
94
94
  vertex_labels=vertex_labels,
95
95
  edge_labels=edge_labels,
96
96
  transform=mpl.transforms.IdentityTransform(),
97
- offset_transform=ax.transData,
98
97
  )
99
- ax.add_artist(nwkart)
100
-
101
- # Set the figure, which itself sets the dpi scale for vertices, edges,
102
- # arrows, etc. Now data limits can be computed correctly
103
- nwkart.set_figure(ax.figure)
104
-
105
98
  artists.append(nwkart)
106
-
107
- # Set normailsed layout since we have it by now
108
99
  layout = nwkart.get_layout()
100
+ else:
101
+ nwkart = None
109
102
 
110
103
  if grouping is not None:
111
104
  grpart = GroupingArtist(
112
105
  grouping,
113
106
  layout,
114
107
  network=network,
115
- transform=ax.transData,
116
108
  )
117
- ax.add_artist(grpart)
118
-
119
- grpart.set_figure(ax.figure)
109
+ layout = grpart.get_layout()
120
110
  artists.append(grpart)
111
+ else:
112
+ grpart = None
113
+
114
+ if (nwkart is not None) or (grpart is not None):
115
+ ndim = layout.shape[1]
116
+ else:
117
+ ndim = None
118
+
119
+ if ax is None:
120
+ if ndim == 3:
121
+ fig = plt.figure(figsize=figsize)
122
+ ax = fig.add_subplot(111, projection="3d")
123
+ else:
124
+ fig, ax = plt.subplots(figsize=figsize)
125
+ ndim = 2
126
+ else:
127
+ # Check that the expected axis projection is used (3d for 3d layouts)
128
+ if ndim == 3:
129
+ assert isinstance(ax, Axes3D)
130
+ elif ndim == 2:
131
+ # NOTE: technically we probably want it to be cartesian (not polar, etc.)
132
+ # but let's be flexible for now and let that request bubble up from users
133
+ assert not isinstance(ax, Axes3D)
134
+
135
+ # This is used in 3D for autoscaling
136
+ had_data = ax.has_data()
137
+
138
+ if nwkart is not None:
139
+ # Set the figure, which itself sets the dpi scale for vertices, edges,
140
+ # arrows, etc. Now data limits can be computed correctly
141
+ nwkart.set_offset_transform(ax.transData)
142
+ ax.add_artist(nwkart)
143
+ nwkart.axes = ax
144
+
145
+ if grpart is not None:
146
+ grpart.set_transform(ax.transData)
147
+ ax.add_artist(grpart)
148
+ grpart.ax = ax
121
149
 
122
150
  if title is not None:
123
151
  ax.set_title(title)
@@ -125,11 +153,11 @@ def network(
125
153
  if aspect is not None:
126
154
  ax.set_aspect(aspect)
127
155
 
128
- _postprocess_axes(ax, artists, strip=strip_axes)
156
+ _postprocess_axes(ax, artists, strip=strip_axes, had_data=had_data)
129
157
 
130
158
  if np.isscalar(margins):
131
- margins = (margins, margins)
132
- if (margins[0] != 0) or (margins[1] != 0):
159
+ margins = [margins] * ndim
160
+ if (margins[0] != 0) or (margins[1] != 0) or ((len(margins) == 3) and (margins[2] != 0)):
133
161
  ax.margins(*margins)
134
162
 
135
163
  return artists
@@ -223,7 +251,6 @@ def tree(
223
251
  show_support=show_support,
224
252
  )
225
253
  ax.add_artist(artist)
226
-
227
254
  artist.set_figure(ax.figure)
228
255
 
229
256
  if title is not None:
@@ -243,26 +270,46 @@ def tree(
243
270
 
244
271
 
245
272
  # INTERNAL ROUTINES
246
- def _postprocess_axes(ax, artists, strip=True):
273
+ def _postprocess_axes(ax, artists, strip=True, had_data=None):
247
274
  """Postprocess axis after plotting."""
248
275
 
249
276
  if strip:
250
- # Despine
251
- ax.spines["right"].set_visible(False)
252
- ax.spines["top"].set_visible(False)
253
- ax.spines["left"].set_visible(False)
254
- ax.spines["bottom"].set_visible(False)
277
+ if not isinstance(ax, Axes3D):
278
+ # Despine
279
+ ax.spines["right"].set_visible(False)
280
+ ax.spines["top"].set_visible(False)
281
+ ax.spines["left"].set_visible(False)
282
+ ax.spines["bottom"].set_visible(False)
255
283
 
256
284
  # Remove axis ticks
257
285
  ax.set_xticks([])
258
286
  ax.set_yticks([])
259
-
260
- # Set new data limits
261
- bboxes = []
262
- for art in artists:
263
- bboxes.append(art.get_datalim(ax.transData))
264
- bbox = mpl.transforms.Bbox.union(bboxes)
265
- ax.update_datalim(bbox)
266
-
267
- # Autoscale for x/y axis limits
268
- ax.autoscale_view()
287
+ if isinstance(ax, Axes3D):
288
+ ax.set_zticks([])
289
+
290
+ # NOTE: bboxes appear to be not that well defined in 3D axes
291
+ # instead, there is a dedicated function that is a little
292
+ # pedestrian
293
+ if isinstance(ax, Axes3D):
294
+ for art in artists:
295
+ XYZ = art.get_layout().values.T
296
+ if ax._zmargin < 0.05 and XYZ[0].size > 0:
297
+ ax.set_zmargin(0.05)
298
+ ax.auto_scale_xyz(
299
+ *XYZ,
300
+ had_data=had_data,
301
+ )
302
+ # NOTE: breaking is not needed, worst case it will
303
+ # autoscale twice (for network and grouping), which
304
+ # is better, at this stage of development, than
305
+ # trying to be too clever by doing the math outselves
306
+ else:
307
+ # Set new data limits
308
+ bboxes = []
309
+ for art in artists:
310
+ bboxes.append(art.get_datalim(ax.transData))
311
+ bbox = mpl.transforms.Bbox.union(bboxes)
312
+ ax.update_datalim(bbox)
313
+
314
+ # Autoscale for x/y axis limits
315
+ ax.autoscale_view()
iplotx/version.py CHANGED
@@ -2,4 +2,4 @@
2
2
  iplotx version information module.
3
3
  """
4
4
 
5
- __version__ = "0.9.0"
5
+ __version__ = "0.10.0"
iplotx/vertex.py CHANGED
@@ -119,6 +119,16 @@ class VertexCollection(PatchCollection):
119
119
  for child in self.get_children():
120
120
  child.set_figure(fig)
121
121
 
122
+ @property
123
+ def axes(self):
124
+ return PatchCollection.axes.__get__(self)
125
+
126
+ @axes.setter
127
+ def axes(self, new_axes):
128
+ PatchCollection.axes.__set__(self, new_axes)
129
+ for child in self.get_children():
130
+ child.axes = new_axes
131
+
122
132
  def get_index(self):
123
133
  """Get the VertexCollection index."""
124
134
  return self._index
@@ -196,7 +206,9 @@ class VertexCollection(PatchCollection):
196
206
  def _update_offsets_from_layout(self) -> None:
197
207
  """Update offsets in matplotlib coordinates from the layout DataFrame."""
198
208
  if self._layout_coordinate_system == "cartesian":
199
- self._offsets = self._layout.values
209
+ # Make sure we accept 3D values and ignore the z component if present
210
+ # This makes life upstream a little more readable
211
+ self._offsets = self._layout.values[:, :2]
200
212
  elif self._layout_coordinate_system == "polar":
201
213
  # Convert polar coordinates (r, theta) to cartesian (x, y)
202
214
  r = self._layout.iloc[:, 0].values
@@ -221,6 +233,16 @@ class VertexCollection(PatchCollection):
221
233
  self._update_offsets_from_layout()
222
234
  self.stale = True
223
235
 
236
+ def set_offset_transform(self, transform: mpl.transforms.Transform) -> None:
237
+ """Set the offset transform for the vertices.
238
+
239
+ Parameters:
240
+ transform: The matplotlib transform to use for the offsets.
241
+ """
242
+ super().set_offset_transform(transform)
243
+ if hasattr(self, "_label_collection"):
244
+ self._label_collection.set_transform(transform)
245
+
224
246
  def get_style(self) -> Optional[dict[str, Any]]:
225
247
  """Get the style dictionary for the vertices."""
226
248
  return self._style
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: iplotx
3
- Version: 0.9.0
3
+ Version: 0.10.0
4
4
  Summary: Plot networkx from igraph and networkx.
5
5
  Project-URL: Homepage, https://github.com/fabilab/iplotx
6
6
  Project-URL: Documentation, https://readthedocs.org/iplotx
@@ -29,7 +29,6 @@ Requires-Python: >=3.11
29
29
  Requires-Dist: matplotlib>=2.0.0
30
30
  Requires-Dist: numpy>=2.0.0
31
31
  Requires-Dist: pandas>=2.0.0
32
- Requires-Dist: pylint>=3.3.7
33
32
  Provides-Extra: igraph
34
33
  Requires-Dist: igraph>=0.11.0; extra == 'igraph'
35
34
  Provides-Extra: networkx
@@ -1,25 +1,28 @@
1
1
  iplotx/__init__.py,sha256=RzSct91jO8abrxOIn33rKEnDUgYpu1oj4olbObgX_hs,489
2
- iplotx/artists.py,sha256=Bpn6NS8S_B_E4OW88JYW6aEu2bIuIQJmbs2paTmBAoY,522
2
+ iplotx/artists.py,sha256=XNtRwuvQdKkZCAejILydLD3J5B87sg5xPXuZFv_Gkk8,654
3
3
  iplotx/cascades.py,sha256=OPqF7Huls-HFmDA5MCF6DEZlUeRVaXsbQcHBoKAgNJs,8182
4
- iplotx/groups.py,sha256=_9KdIiTAi1kXtd2mDywgBJCbqoRq2z-5fzOPf76Wgb8,6287
5
- iplotx/label.py,sha256=6am3a0ejcW_bWEXSOODE1Ke3AyCU1lJ45RfnXNbHAQw,8923
4
+ iplotx/groups.py,sha256=X0G-EULkd7WBn1j82r-cBgpzZRd7gQ1cfqFoYNweLns,6775
5
+ iplotx/label.py,sha256=76vSaH9zPv8drpzFaWNwuEIMQPEgKmilwfBnA8I_BJ4,9307
6
6
  iplotx/layout.py,sha256=KxmRLqjo8AYCBAmXez8rIiLU2sM34qhb6ox9AHYwRyE,4839
7
- iplotx/network.py,sha256=SGmXXrFxqgOoQcEJSZdL3WiI6rHDlPOGg5loGPrYpDk,11688
8
- iplotx/plotting.py,sha256=imlJZdx3S9B59TQPqrHEwQwJEnpI9SljthK34n3QJQY,11007
7
+ iplotx/network.py,sha256=_yEArzsqnzm5MefVKKM96q_Od47ZIwjkJb2wuVFnfD8,13486
8
+ iplotx/plotting.py,sha256=icEefWJnS2lEGLp4t1LhDSP40JuvNKgOie3FDLOnTMk,13195
9
9
  iplotx/tree.py,sha256=TxbNoBHS0CfswrcMIWCNtnOl_3e4-PwCrVo0goywC0U,28807
10
10
  iplotx/typing.py,sha256=QLdzV358IiD1CFe88MVp0D77FSx5sSAVUmM_2WPPE8I,1463
11
- iplotx/version.py,sha256=rlV8GqlJtRzwlHxPle9bW-H7xuYNreaGGD2bFrax930,66
12
- iplotx/vertex.py,sha256=hqdlD9fRBSwH5bRvlpaaPu7jgUR4z9nob1SYfPWDxtI,14966
13
- iplotx/edge/__init__.py,sha256=AVnLsrDWWCkix1LVhrjpWKEKDxOp8joM4tF6RqEHC8I,27115
11
+ iplotx/version.py,sha256=YEqH52lnz6XyxsG7HXlFaHzcWyc3-VsDrQeE7vZtRQQ,67
12
+ iplotx/vertex.py,sha256=rIg1gdxv7ZW8HjqmwJaynm098HqTmlC9XQgB81wjzgk,15775
13
+ iplotx/art3d/edge.py,sha256=cZzI0nPTglU1xA_TsySrdE5GwxVx7smc32mxCE_EP48,1785
14
+ iplotx/art3d/vertex.py,sha256=KhwR60ekPLL1CDYn9jeQFo5kfdCS5Naz7u1kM-_eq7U,1883
15
+ iplotx/edge/__init__.py,sha256=P96eXHECrqHtVeIxdBA0SxJvTMeHlXPP_bqEOi5MsVQ,27589
14
16
  iplotx/edge/arrow.py,sha256=ZKt3UNZ7XRa2S3KxpoQfd4q_6eSUHOS476BZNqlf2pw,16462
15
- iplotx/edge/geometry.py,sha256=wpFTi12-BaUaWr6Ie-nHV_SMAdSGJvjzJaqeEaSPf9w,15053
17
+ iplotx/edge/geometry.py,sha256=G0hze1SQGUiiLMdc8QVO7zr1C9UUIQt-IN17KBk6lkM,16317
18
+ iplotx/edge/geometry3d.py,sha256=HnL1TvMXFegvco6oaiUqDXRKbx9GW3FsT4DUX_Ol94k,3207
16
19
  iplotx/edge/leaf.py,sha256=SyGMv2PIOoH0pey8-aMVaZheK3hNe1Qz_okcyWbc4E4,4268
17
20
  iplotx/edge/ports.py,sha256=BpkbiEhX4mPBBAhOv4jcKFG4Y8hxXz5GRtVLCC0jbtI,1235
18
21
  iplotx/ingest/__init__.py,sha256=S0YfnXcFKseB7ZBQc4yRt0cNDsLlhqdom0TmSY3OY2E,4756
19
22
  iplotx/ingest/heuristics.py,sha256=715VqgfKek5LOJnu1vTo7RqPgCl-Bb8Cf6o7_Tt57fA,5797
20
23
  iplotx/ingest/typing.py,sha256=61LwNwrTHVh8eqqC778Gr81zPYcUKW61mDgGCCsuGSk,14181
21
- iplotx/ingest/providers/network/igraph.py,sha256=8dWeaQ_ZNdltC098V2YeLXsGdJHQnBa6shF1GAfl0Zg,2973
22
- iplotx/ingest/providers/network/networkx.py,sha256=4sPFOx87ipOYlXu0hjJl25Z4So_RnhO1CYYozGp-wJg,4626
24
+ iplotx/ingest/providers/network/igraph.py,sha256=WL9Yx2IF5QhUIoKMlozdyq5HWIZ-IJmNoeS8GOhL0KU,2945
25
+ iplotx/ingest/providers/network/networkx.py,sha256=ehCg4npL073HX-eAG-VoP6refLPsMb3lYG51xt_rNjA,4636
23
26
  iplotx/ingest/providers/network/simple.py,sha256=e_aHhiHhN9DrMoNrt7tEMPURXGhQ1TYRPzsxDEptUlc,3766
24
27
  iplotx/ingest/providers/tree/biopython.py,sha256=4N_54cVyHHPcASJZGr6pHKE2p5R3i8Cm307SLlSLHLA,1480
25
28
  iplotx/ingest/providers/tree/cogent3.py,sha256=JmELbDK7LyybiJzFNbmeqZ4ySJoDajvFfJebpNfFKWo,1073
@@ -33,6 +36,6 @@ iplotx/utils/geometry.py,sha256=6RrC6qaB0-1vIk1LhGA4CfsiMd-9JNniSPyL_l9mshE,9245
33
36
  iplotx/utils/internal.py,sha256=WWfcZDGK8Ut1y_tOHRGg9wSqY1bwSeLQO7dHM_8Tvwo,107
34
37
  iplotx/utils/matplotlib.py,sha256=wELE73quQv10-1w9uA5eDTgkZkylJvjg7pd3K5tZPOo,6294
35
38
  iplotx/utils/style.py,sha256=vyNP80nDYVinqm6_9ltCJCtjK35ZcGlHvOskNv3eQBc,4225
36
- iplotx-0.9.0.dist-info/METADATA,sha256=HQtb9YO4hhXGn0K8gaXBIAerAu1Eu0b4QiIHWCIZv2c,4908
37
- iplotx-0.9.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
38
- iplotx-0.9.0.dist-info/RECORD,,
39
+ iplotx-0.10.0.dist-info/METADATA,sha256=BY0tMOjP84ydubHd9ocmpn9LaqdmoqX3VcBEX_6tTWA,4880
40
+ iplotx-0.10.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
41
+ iplotx-0.10.0.dist-info/RECORD,,