所以,我从here - 程序3获得了关于如何生成网络图的代码。我已经调整了它,以便与图形相距一定距离的每个节点都以不同的颜色呈现
import networkx as net
import matplotlib.pyplot as plt
from collections import defaultdict
import math
#%matplotlib inline
twitter_network = [ line.strip().split('\t') for line in file('twitter_network.csv') ]
o = net.DiGraph()
hfollowers = defaultdict(lambda: 0)
for (twitter_user, followed_by, followers) in twitter_network:
o.add_edge(twitter_user, followed_by, followers=int(followers))
hfollowers[twitter_user] = int(followers)
SEED = 'NitinJamadagni'
#centre around the SEED node and set radius of graph
g = net.DiGraph(net.ego_graph(o, SEED, radius=4))
#modified trim functions
def trim_degrees_ted(g, degree=1):
g2 = g.copy()
d = net.degree(g2)
for n in g2.nodes():
if n == SEED: continue # don't prune the SEED node
if d[n] <= degree:
g2.remove_node(n)
return g2
def trim_edges_ted(g, weight=1):
g2 = net.DiGraph()
for f, to, edata in g.edges_iter(data=True):
if f == SEED or to == SEED: # keep edges that link to the SEED node
g2.add_edge(f, to, edata)
elif edata['followers'] <= weight:
g2.add_edge(f, to, edata)
return g2
print 'g: ', len(g)
core = trim_degrees_ted(g, degree=0)
print 'core after node pruning: ', len(core)
core = trim_edges_ted(core, weight=300)
print 'core after edge pruning: ', len(core)
nodeset_types = { 0:'nil',1:'nil',2:'nil' }
shit = net.shortest_path_length(o,SEED)
nodesets = defaultdict(list)
for tt,ty in nodeset_types.iteritems():
nodesets[tt] = [ x[0] for x in shit.iteritems() if x[1]==int(tt) ]
pos = net.spring_layout(core) # compute layout
colours = ['yellow','red','green']
plt.figure(figsize=(18,18))
plt.axis('off')
i = 0
#different color for each node
for k in range[0,3]:
net.draw_networkx_nodes(core, pos, nodelist=[x[0] for x in shit.iteritems() if x[1] == k], node_size=int(10/(k+1)), node_color=colours[k])
net.draw_networkx_edges(core, pos, width=0.5, alpha=0.5)
alphas = { 0: 1.0, 1: 0.5, 2: 0.5}
for k in nodesets.keys():
for n in nodesets[k]:
x, y = pos[n]
plt.text(x, y+0.02, s=n, alpha=alphas[k], horizontalalignment='center', fontsize=9)
plt.savefig("path.png")
跑步 - python filename.py
它给出了一个图表,其中所有节点都是黄色并且在终端上输出
g: 142
core after node pruning: 142
core after edge pruning: 142
Not TED 142
TED 0
colourmap: {'Not TED': 'yellow', 'TED': 'red'}
在解释器中逐行运行时,我收到错误 -
for k in range[0,3]:
... net.draw_networkx_nodes(core, pos, nodelist=[x[0] for x in shit.iteritems() if x[1] == k], node_size=int(10/(k+1)), node_color=colours[k])
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
答案 0 :(得分:0)
使用parens而非方括号,range
是一个函数:
for k in range(0,3): # <- correct
for k in range[0,3]: # < wrong