繁体   English   中英

在networkx中着色步行边缘

[英]Coloring walk edges in networkx

我已经编写了一个简单的代码,使用networkx库在给定的图形G中生成随机游走。现在,当我走路时,我希望边缘变为彩色并使用matplotlib绘制..在循环中说。 例如:假设我从连接边缘从节点1走到节点2,我希望该边缘的颜色与其他边缘不同。 下面是代码:

def unweighted_random_walk(starting_point,ending_point, graph):
'''
starting_point: String that represents the starting point in the graph
ending_point: String that represents the ending point in the graph
graph: A NetworkX Graph object
'''
##Begin the random walk
current_point=starting_point
#current_node=graph[current_point]
current_point_neighors=graph.neighbors(current_point)
hitting_time=0

#Determine the hitting time to get to an arbitrary neighbor of the
#starting point
while current_point!=ending_point:
    #pick one of the edges out of the starting_node with equal probs
    possible_destination=current_point_neighbors[random.randint(0,current_point_neighors)]
    current_point=possible_destination
    current_point_neighbors=graph.neighbors(current_point)
    hitting_time+=1
return hitting_time

这是我使用的:

def colors(G):
    colors = []
    for edge,data in G.edges_iter(data=True):
        # return a color string based on whatever property you want
        return 'red' if data['someproperty'] else 'blue'

        # alternatively you could store a 'color' key on the edge
        # return data['color']

    return colors

# When you invoke the draw command pass a list of edge colors
nx.draw_spectral(G, edge_color=colors(G))

这工作正常......但是,请小心使用适当的值填充列表。 对有效代码的修改是:

def colors(G, attrib):
   colors = []    
   for node,data in G.nodes_iter(data=True):
     # return a color string based on whatever property you want
     if data['someproperty'] != attrib:
        colors.append('AliceBlue')
     else:
        colors.append('Crimson')
   return colors

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM