[英]Coloring of nodes based on depth from root node
我在使用networkx的python上有一個圖表
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)
我有一個root定義 - 這是twitter用戶的名字
SEED = 'BarackObama'
我已經從SEED初始化了一個子圖
g = net.DiGraph(net.ego_graph(o, SEED, radius=4))
現在,我想根據SEED的深度為節點指定顏色並繪制它。 我該怎么做呢 ?
在下面的代碼中,我創建了一個圖表。 然后我從該圖中獲得每個節點的距離。 然后我將其反轉,以便相反,對於每個距離,我在該距離處有一個節點列表。 然后,對於每個距離,我繪制具有給定顏色的節點。 請注意,如果存在無法訪問的節點,則不會對其進行繪制。 如果存在這樣的節點,您需要分別決定您正在使用它們。
另外因為我只使用標准顏色(白色除外),所以我只能做幾個距離。 如果你需要更多,那么你將不得不使用其他方式來制作你的顏色列表(或者根據距離制作一個返回顏色的函數)。 它將采用RGB或HEX定義顏色。
G=nx.erdos_renyi_graph(10,0.4)
G.add_node(11) # here's a new node, it's not connected
SEED=1
distanceDict = nx.shortest_path_length(G, SEED) #for each node know how far it is
inverse_dict = {} #for each distance this will say which nodes are there.
for k,v in distanceDict.iteritems():
inverse_dict[v] = inverse_dict.get(v,[])
inverse_dict[v].append(k)
inverse_dict
> {0: [1], 1: [0, 5, 6], 2: [2, 3, 4, 8, 9], 3: [7]}
colors = ['r', 'b', 'g', 'k', 'c', 'm']#create a list of colors
pos = nx.spring_layout(G) #set positions so that each plot below uses same position
for distance in inverse_dict.keys():
if distance<=len(colors): #plot these nodes with the right color
nx.draw_networkx(G, pos = pos, nodelist = inverse_dict[distance], node_color = colors[distance])
tooFar = []
for node in G.nodes_iter():
if node not in distanceDict or distanceDict[node]>max_dist:
tooFar.append(node)
nx.draw_networkx(G,pos=pos, nodelist=tooFar, node_color='w')
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.