Python 2.7 向边或节点添加颜色不会';你不在networkx工作吗?
我用了这个问题的答案: 但它不起作用,我基本上就是这样使用它的:Python 2.7 向边或节点添加颜色不会';你不在networkx工作吗?,python-2.7,networkx,Python 2.7,Networkx,我用了这个问题的答案: 但它不起作用,我基本上就是这样使用它的: myGraph.add_node(name , color="blue" , style='filled',fillcolor='blue', shape='square') nx.draw(myGraph, with_labels=True, font_weight='bold') plt.show() 但是输出图形根本没有任何颜色,我做错了什么?它也不适用于add_edge,完全没有颜色。我正在使用Py
myGraph.add_node(name , color="blue" , style='filled',fillcolor='blue', shape='square')
nx.draw(myGraph, with_labels=True, font_weight='bold')
plt.show()
但是输出图形根本没有任何颜色,我做错了什么?它也不适用于add_edge,完全没有颜色。我正在使用Python2.7(我不能使用3+)
我不想同时添加所有颜色,我需要在一次添加一个节点/边的同时添加颜色。当您使用
networkx
绘制时,为在Graphviz
中绘制彩色节点而指向的链接。您需要指定颜色序列,并将该值提供给node\u color
属性,以nx.draw
,如下所示:
import matplotlib.pyplot as plt
import networkx as nx
myGraph = nx.path_graph(n=5)
# Add your node. You can add more nodes if you want,
# just remember to specify the color for the new nodes,
# else they will get the default color
name = "colored_Node"
myGraph.add_node(name,
color='green',
style='filled',
fillcolor='blue',
shape='square')
# Get the colored dictionary
colored_dict = nx.get_node_attributes(myGraph, 'color')
# Create a list for all the nodes
default_color = 'blue'
color_seq = [colored_dict.get(node, default_color) for node in myGraph.nodes()]
# Pass the color sequence
nx.draw(myGraph, with_labels=True, font_weight='bold', node_color=color_seq)
plt.show()
下面是一个示例图:参考资料: