-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathplot_net.py
296 lines (225 loc) · 7.9 KB
/
plot_net.py
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
"""
Created on Tue Aug 27 2014
@author: rkp, wronk, sidh0
"""
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import network_compute
def plot_connected_components(ax, G):
"""
Plot a distribution of the connected component sizes for a graph.
Args:
G: A networkx graph object.
Returns:
figure handle & axis.
"""
# Calculate list of connected component sizes
cc_sizes = [len(nodes) for nodes in nx.connected_components(G)]
# Sort connected component sizes & plot them
cc_sizes_sorted = sorted(cc_sizes, reverse=True)
# Open plots
fig, ax = plt.subplots(1, 1)
ax.scatter(np.arange(len(cc_sizes_sorted)), cc_sizes_sorted, s=20, c='r')
def plot_node_btwn(G, bins=20, ranked=False):
"""
Plot the node-betweenness distributions.
Args:
G: networkx graph object
Returns:
figure handle & axes array.
"""
# Calculate node-betweenness
node_btwn_dict = nx.betweenness_centrality(G)
# Sort node-betweenness dictionary by node-betweenness values
node_btwn_labels_sorted, node_btwn_vec_sorted = \
network_compute.get_ranked(node_btwn_dict)
# Open figure & axes
if ranked:
fig, axs = plt.subplots(2, 1, facecolor='w')
# Plot histogram
axs[0].hist(node_btwn_vec_sorted, bins)
axs[0].set_ylabel('Occurrences')
axs[0].set_xlabel('Node-betweenness')
# Plot sorted node between values
axs[1].scatter(np.arange(len(node_btwn_vec_sorted)),
node_btwn_vec_sorted, s=20, c='r')
axs[1].set_xlabel('Area')
axs[1].set_ylabel('Node-betweenness')
return fig, axs
else:
fig, ax = plt.subplots(1, 1, facecolor='w')
# Plot histogram
ax.hist(node_btwn_vec_sorted, bins=bins)
ax.set_xlabel('Betweenness centrality')
ax.set_ylabel('Occurrences')
ax.set_title('Betweenness centrality')
return fig, ax
def plot_edge_btwn(G, bins=20):
"""
Plot the edge-betweenness distributions.
Args:
G: networkx graph object
Returns:
figure handle & axes array.
"""
# Get edge-betweenness dictionary
edge_btwn_dict = nx.edge_betweenness_centrality(G)
# Sort edge-betweenness dictionary by edge-betweenness values
edge_btwn_labels_sorted, edge_btwn_vec_sorted = \
network_compute.get_ranked(edge_btwn_dict)
# Open figure & axes
fig, axs = plt.subplots(2, 1)
# Plot histogram
axs[0].hist(edge_btwn_vec_sorted, bins)
axs[0].set_ylabel('Occurrences')
axs[0].set_xlabel('Edge-betweenness')
# Plot sorted node between values
axs[1].scatter(np.arange(len(edge_btwn_vec_sorted)),
edge_btwn_vec_sorted, s=20, c='r')
axs[1].set_xlabel('Area')
axs[1].set_ylabel('Edge-betweenness')
return fig, axs
def plot_out_in_ratios(W_net, labels=None, bins=20):
"""
Plot a distribution of output/input connection ratios for a given
network (defined by a weight matrix W_net)
"""
if labels is None:
labels = np.arange(W_net.shape[0])
# Calculate total output & input connections for each node
_,_,out_in_dict = network_compute.out_in(W_net, labels,binarized=False)
# Calculate ranked output/input ratios
out_in_labels_sorted, out_in_vec_sorted = \
network_compute.get_ranked(out_in_dict)
# Open figure & axes
fig, axs = plt.subplots(2, 1)
# Plot histogram
axs[0].hist(out_in_vec_sorted, bins)
axs[0].set_ylabel('Occurrences')
axs[0].set_xlabel('Output/Input')
# Plot sorted input/output ratios
axs[1].scatter(np.arange(len(out_in_vec_sorted)),
out_in_vec_sorted, s=20, c='r')
axs[1].set_xlabel('Area')
axs[1].set_ylabel('Output/Input')
return fig, axs
def plot_clustering_coeff_pdf(ax, G, bins=np.linspace(0., 1, 50)):
'''
Plot clustering coefficient probability density function
Parameters
----------
G : networkx graph object
graph to calculate clustering coefficients of
bins : array | list
bin edges for histogram
Returns
--------
fig : fig
figure object of distribution histogram for plotting
'''
ccoeff_dict = nx.clustering(G)
ccoeffs = np.array(ccoeff_dict.values())
#TODO Need to normalize coefficients?
# Plot coefficients according to bins
ax.hist(ccoeffs, bins)
ax.set_title('Clustering coefficient')
ax.set_xlabel('Clustering coefficient')
ax.set_ylabel('Occurrences')
def plot_clustering_coeff_ranked(ax, G, num_ranked=10):
'''
Plot clustering coefficient ranked by maximum value
Parameters
----------
G : networkx graph object
graph to get clustering coefficients for
num_ranked : int
number of ranked brain areas to show
Returns
--------
fig : fig
figure object of distribution histogram for plotting
'''
# Get clustering coefficients
ccoeff_dict = nx.clustering(G)
# Graph params width = 0.5
xpos = np.arange(num_ranked)
width = 0.8
# Constuct figure
fig, ax = plt.subplot(1, 1)
sorted_tups = sorted(zip(ccoeff_dict.values(), ccoeff_dict.keys()),
key=lambda tup: tup[0], reverse=True)[:num_ranked]
# Plot top ranked coefficients according to bins
ax.bar(xpos, [w for w, _ in sorted_tups], fc='green',
width=width, alpha=.8)
ax.xticks(xpos + width / 2., [n for _, n in sorted_tups])
ax.set_title('Ranked Clustering Coefficients')
plt.set_xlabel('Region')
plt.set_ylabel('Clustering Coefficient')
def plot_connection_strength(ax, W, bins=10):
'''
Generate figure/axis and plots a histogram of connection strength
Parameters
----------
W : 2-D array
weight matrix
Returns
--------
fig, ax : fig, ax
plotting objects showing distribution of connection strengths
'''
W_new = W[W > 0]
W_new = W[~(np.isinf(W) + np.isnan(W))]
binnedW, bins, patches = plt.hist(W_new, bins, facecolor='red', alpha=0.5)
ax.set_xlabel('Weight value')
ax.set_ylabel('Frequency')
ax.set_title('Connection strength')
def plot_shortest_path_distribution(ax, G):
'''
Generate figure/axis and plots a bar graph of shortest path distribution
Parameters
----------
G -- A graph object
Returns
--------
fig, ax : fig, ax
plotting objects showing distribution of shortest paths
'''
SP = nx.shortest_path_length(G)
names = G.nodes()
SP_values = [SP[entry].values() for entry in SP]
All_SP_values = [item for sublist in SP_values for item in sublist]
uniques = np.unique(All_SP_values)
int_uniques = [int(entry) for entry in uniques]
counts = []
for j in range(len(uniques)):
current = uniques[j]
counts.append(sum(All_SP_values == current))
ax.bar(uniques, counts)
ax.set_xlabel('Number of nodes in shortest path')
ax.set_ylabel('Frequency')
ax.set_xticks(uniques + 0.4)
ax.set_xticklabels(int_uniques)
ax.set_title('Distribution of shortest path lengths')
def plot_degree_distribution(ax, G, bins=np.linspace(0, 140, 50)):
''' Plots the degree distribution of a graph object '''
degrees = G.degree().values()
ax.hist(degrees, bins)
ax.set_xlabel('Degree')
ax.set_ylabel('Occurrences')
ax.set_title('Degree distribution')
def line_hist(ax, G, feature, bins, **kwargs):
"""Plot a histogram of a specified feature as a line on specified axis"""
# Get data vector to use
if feature == 'degree':
data_vec = G.degree().values()
elif feature == 'ccoeff':
data_vec = nx.clustering(G).values()
elif feature == 'node_btwn':
data_vec = nx.betweenness_centrality(G).values()
# Calculate histogram
cts, bins = np.histogram(data_vec, bins)
# Get bin centers
bcents = .5 * (bins[:-1] + bins[1:])
# Plot line
ax.plot(bcents, cts, **kwargs)