Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

plot.py 7.8 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
  1. import sys
  2. import numpy as np
  3. import pandas as pd
  4. import networkx as nx
  5. import matplotlib.pyplot as plt
  6. import plotly
  7. import plotly.offline as py
  8. import plotly.io as pio
  9. class GraphNetwork:
  10. """An object that builds a network graph in Plotly with Networkx including functions that display node and edge attributes.
  11. Object requires a graph built with Networkx. If node and edge attributes are to be added to the visualization those attributes need to be added to the graph.
  12. """
  13. def __init__(self, G):
  14. self.G = G
  15. # Get the location of the nodes
  16. self.pos = nx.spring_layout(self.G)
  17. def trace_nodes(self, node_color_variable=None, node_text=None):
  18. """Create a function to build a dictionary to trace nodes, including the color and text when hovering over an edge.
  19. :param node_color_variable: The name of the variable that distinguishes nodes by color.
  20. The values of the colors are represented as integers.
  21. Default equals None when no color is assigned to the nodes.
  22. :type node_color_variable: str
  23. :param node_text: The hover text corresponding to each node.
  24. The list of strings consists of multiple node attributes each attribute separated by <br> to indicate a new line.
  25. The list should be ordered by the order in which the nodes appear as in G.nodes().
  26. The default node text equals None, which means that the name of the node is used when hovering over the node.
  27. :type node_text: list of strings
  28. """
  29. # color nodes by category (where category is a number)
  30. if node_color_variable:
  31. node_colors = list(nx.get_node_attributes(self.G, node_color_variable).values())
  32. else:
  33. node_colors = []
  34. # set node text
  35. if node_text:
  36. node_text = node_text
  37. else:
  38. node_text = []
  39. for node in self.G.nodes():
  40. node_text.append("Name: " + node)
  41. # Extract node positions by coordinates
  42. Xn = [self.pos[k][0] for k in self.pos.keys()]
  43. Yn = [self.pos[k][1] for k in self.pos.keys()]
  44. self.trace_nodes = dict(
  45. type='scatter',
  46. x=Xn,
  47. y=Yn,
  48. mode="markers",
  49. marker=dict(size=10, color=node_colors),
  50. hoverinfo='text',
  51. text=node_text
  52. )
  53. def trace_edges(self, edge_text=None, edge_attribute=None):
  54. """Create a function to build a dictionary to trace edges, including the text when hovering over an edge.
  55. :param edge_text: The hover text corresponding to each edge.
  56. The list of strings consists of multiple edge attributes each attribute separated by <br> to indicate a new line.
  57. The list should be ordered by the order in which the edges appear as in G.edges().
  58. :type edge_text: list of strings, default=None
  59. :param edge_attribute: The name of the variable to show as a single edge attribute when hovering over the edge.
  60. When edge_text equals None AND edge_attribute equals None, no edge attributes are shown.
  61. :type edge_attribute: str, default=None
  62. """
  63. # set edge text
  64. if edge_text:
  65. hover_info = 'text'
  66. edge_text = edge_text
  67. hover_template = None
  68. elif edge_attribute:
  69. hover_info = 'text'
  70. edge_text = nx.get_edge_attributes(self.G, edge_attribute)
  71. edge_text = list(edge_text.values())
  72. hover_template = '{}: %{edge_text}'.format(edge_attribute)
  73. else:
  74. hover_info = None
  75. edge_text = None
  76. hover_template = None
  77. Xe=[]
  78. Ye=[]
  79. Xtext = []
  80. Ytext = []
  81. for e in self.G.edges():
  82. Xe.extend([self.pos[e[0]][0], self.pos[e[1]][0], None])
  83. Ye.extend([self.pos[e[0]][1], self.pos[e[1]][1], None])
  84. Xtext.append((self.pos[e[0]][0] + self.pos[e[1]][0])/2)
  85. Ytext.append((self.pos[e[0]][1] + self.pos[e[1]][1])/2)
  86. self.trace_edges = dict(
  87. type='scatter',
  88. mode='lines',
  89. x=Xe,
  90. y=Ye,
  91. line=dict(width=1, color='#555555')
  92. )
  93. self.trace_edge_text = dict(
  94. type='scatter',
  95. mode='markers',
  96. x=Xtext,
  97. y=Ytext,
  98. marker_size=0.5,
  99. hoverinfo=hover_info,
  100. text=edge_text,
  101. hovertemplate=hover_template
  102. )
  103. def visualization_attributes(self, title=str):
  104. """Set axis attributes.
  105. Default to hiding axis lines, hiding grid, hiding ticklabels.
  106. Paramaters
  107. ------------------
  108. :param title: Title of the graph network plot.
  109. :type title: str
  110. :param showline: Defaults to False
  111. :type showline: bool
  112. :param zeroline: Defaults to False
  113. :type zeroline: bool
  114. :param showgrid: Defaults to False
  115. :type showgrid: bool
  116. :param showticklabels: Defaults to False
  117. :type showticklabels: bool
  118. :param width: Width of the plot.
  119. :type width: int
  120. :param height: Height of the plot.
  121. :type height: int
  122. :param autosize: Defaults to False
  123. :type autosize: bool
  124. :param showlegend: Defaults to False
  125. :type showlegend: bool
  126. :param margin: l=40,r=40,b=85,t=100,pad=0
  127. :type margin: dictionary of key : int value pairs
  128. :param hovermode: When hovermode equals 'closest' a single hover label appears for the point directly underneath the cursor.
  129. Defaults to 'closest'.
  130. :type hovermode: {'closest'}
  131. :param plot_bgcolor: Set background color.
  132. Defaults to '#ffffff'
  133. :type plot_bgcolor: str
  134. """
  135. axis = dict(
  136. showline=False, # hide axis line, grid, ticklabels, title
  137. zeroline=False,
  138. showgrid=False,
  139. showticklabels=False,
  140. title=''
  141. )
  142. self.layout = dict(
  143. title=title,
  144. width=600,
  145. height=600,
  146. autosize=False,
  147. showlegend=False,
  148. xaxis=axis,
  149. yaxis=axis,
  150. margin=dict(l=40,r=40,b=85,t=100,pad=0,),
  151. hovermode='closest',
  152. plot_bgcolor='#ffffff', #set background color
  153. )
  154. def draw_network(self, graph_filename='graph.html'):
  155. """Draw the network.
  156. :param graph_filename: Name and location of the filename as 'html'.
  157. :type graph_filename: str, default='graph.html'
  158. :return: Output file with '.html' extension.
  159. """
  160. fig = dict(
  161. data=[
  162. self.trace_nodes,
  163. self.trace_edges,
  164. self.trace_edge_text
  165. ],
  166. layout=self.layout
  167. )
  168. pio.write_html(fig, graph_filename)
  169. # if __name__ == '__main__':
  170. # plot = GraphNetwork(G)
  171. # plot.trace_edges()
  172. # plot.trace_nodes()
  173. # plot.visualization_attributes()
  174. # plot.draw_network()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...