|
1
|
|
|
import networkx as nx |
|
2
|
|
|
from matplotlib import pyplot |
|
3
|
|
|
|
|
4
|
|
|
from ..color import node_color_mapping |
|
5
|
|
|
|
|
6
|
|
|
|
|
7
|
|
|
def draw(graph: nx.Graph, |
|
8
|
|
|
with_node_labels: bool = True, |
|
9
|
|
|
with_edge_labels: bool = False, |
|
10
|
|
|
**kwargs): |
|
11
|
|
|
""" |
|
12
|
|
|
Draws the given networkx graph with optional node and edge labels. |
|
13
|
|
|
|
|
14
|
|
|
Parameters: |
|
15
|
|
|
graph (nx.Graph): The input graph to be drawn. |
|
16
|
|
|
with_node_labels (bool): Whether to display node labels. Default is True. |
|
17
|
|
|
with_edge_labels (bool): Whether to display edge labels. Default is False. |
|
18
|
|
|
|
|
19
|
|
|
Returns: |
|
20
|
|
|
None |
|
21
|
|
|
""" |
|
22
|
|
|
pos = nx.planar_layout(graph) if nx.is_planar(graph) else None |
|
23
|
|
|
pos = nx.spring_layout(graph, pos=pos) if pos else nx.spring_layout(graph) |
|
24
|
|
|
|
|
25
|
|
|
draw_params = {} |
|
26
|
|
|
if with_node_labels: |
|
27
|
|
|
draw_params.update( |
|
28
|
|
|
{ |
|
29
|
|
|
'with_labels': True, |
|
30
|
|
|
'labels': nx.get_node_attributes(graph, 'label'), |
|
31
|
|
|
'font_size': 6, |
|
32
|
|
|
'font_color': 'blue', |
|
33
|
|
|
# 'horizontalalignment':'left', |
|
34
|
|
|
# 'verticalalignment':'bottom', |
|
35
|
|
|
# 'bbox': { |
|
36
|
|
|
# 'boxstyle': 'round', |
|
37
|
|
|
# 'fc': (0.02, 0.02, 0.02), |
|
38
|
|
|
# 'lw': 0, |
|
39
|
|
|
# 'alpha': 0.15, |
|
40
|
|
|
# 'path_effects': [patheffects.withStroke(linewidth=1, foreground="red")] |
|
41
|
|
|
# } |
|
42
|
|
|
} |
|
43
|
|
|
) |
|
44
|
|
|
|
|
45
|
|
|
node_color = list(node_color_mapping(graph).values()) |
|
46
|
|
|
nx.draw(graph, pos, node_color=node_color, **draw_params) |
|
47
|
|
|
if with_edge_labels: |
|
48
|
|
|
nx.draw_networkx_edge_labels(graph, |
|
49
|
|
|
pos, |
|
50
|
|
|
edge_labels=nx.get_edge_attributes(graph, 'label'), |
|
51
|
|
|
font_color='red', |
|
52
|
|
|
font_size=6) |
|
53
|
|
|
|
|
54
|
|
|
|
|
55
|
|
|
def plot(graph: nx.Graph, |
|
56
|
|
|
with_node_labels: bool = True, |
|
57
|
|
|
with_edge_labels: bool = False, |
|
58
|
|
|
**kwargs): |
|
59
|
|
|
""" |
|
60
|
|
|
Plots the given networkx graph with optional node and edge labels. |
|
61
|
|
|
|
|
62
|
|
|
Args: |
|
63
|
|
|
graph (nx.Graph): The input graph to be plotted. |
|
64
|
|
|
with_node_labels (bool): Whether to display node labels. Default is True. |
|
65
|
|
|
with_edge_labels (bool): Whether to display edge labels. Default is False. |
|
66
|
|
|
|
|
67
|
|
|
Returns: |
|
68
|
|
|
None |
|
69
|
|
|
""" |
|
70
|
|
|
draw(graph, with_node_labels, with_edge_labels, **kwargs) |
|
71
|
|
|
|
|
72
|
|
|
ax = pyplot.gca() |
|
73
|
|
|
ax.margins(0.10) |
|
74
|
|
|
|
|
75
|
|
|
fig = pyplot.gcf() |
|
76
|
|
|
fig.suptitle(graph.name) |
|
77
|
|
|
fig.tight_layout() |
|
78
|
|
|
|
|
79
|
|
|
# pyplot.axis("off") |
|
80
|
|
|
pyplot.show() |
|
81
|
|
|
|