Debian Codegraph @

examples/02-plot/graph_network.py

raw
1 """
2 .. _graph_network_example:
3
4 Plot a 3D Graph Network
5 ~~~~~~~~~~~~~~~~~~~~~~~
6
7 Render a node-edge network with labels and weighted edges using
8 :func:`pyvista.line_segments_from_points`.
9 """
10
11 import numpy as np
12 import pyvista as pv
13
14 # sphinx_gallery_start_ignore
15 # point labels are static-only in the docs
16 PYVISTA_GALLERY_FORCE_STATIC_IN_DOCUMENT = True
17 # sphinx_gallery_end_ignore
18
19 # %%
20 # Define nodes and weighted edges
21 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
22 # Six labeled nodes connected by seven weighted edges.
23
24 labels = ['A', 'B', 'C', 'D', 'E', 'F']
25 points = np.array(
26 [
27 (-0.8, 0.0, 0.0),
28 (-0.1, 0.7, 0.3),
29 (-0.1, -0.7, 0.2),
30 (0.8, 0.9, 0.6),
31 (0.9, -0.1, 0.8),
32 (0.8, -0.9, 0.1),
33 ],
34 )
35 edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 4), (2, 5), (4, 5)]
36 weights = np.array([0.9, 0.7, 1.2, 0.8, 1.0, 0.6, 1.1])
37
38 segments = np.vstack([points[[start, stop]] for start, stop in edges])
39 graph = pv.line_segments_from_points(segments)
40 graph.cell_data['weight'] = weights
41
42
43 # %%
44 # Render the network
45 # ~~~~~~~~~~~~~~~~~~
46 # Edges are colored by weight; node labels stay anchored to their points.
47
48 pl = pv.Plotter()
49 pl.add_mesh(
50 graph,
51 scalars='weight',
52 cmap='viridis',
53 line_width=8,
54 render_lines_as_tubes=True,
55 )
56 pl.add_points(points, color='black', point_size=16, render_points_as_spheres=True)
57 pl.add_point_labels(points, labels, font_size=24, point_size=0, fill_shape=False)
58 pl.show()
59 # %%
60 # .. tags:: plot