为边缘或节点添加颜色在 networkx 中不起作用?
Adding color to edges or nodes doesn't work in networkx?
我用了这个问题的答案:
Color a particular node in Networkx and Graphviz
但它不起作用,我基本上就是这样使用它的:
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,根本没有颜色。我正在使用 python 2.7(我不能使用 3+)
而且我不想同时添加所有颜色,我需要在一次添加 nodes/edges 时添加颜色。
您在 Graphviz
中绘制彩色节点时指出的 link,而您使用 networkx
进行绘制。您需要指定一个颜色序列并将该值提供给 node_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()
这是一个示例图:
.
参考文献:
- Color nodes in NetworkX graph
我用了这个问题的答案:
Color a particular node in Networkx and Graphviz
但它不起作用,我基本上就是这样使用它的:
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,根本没有颜色。我正在使用 python 2.7(我不能使用 3+)
而且我不想同时添加所有颜色,我需要在一次添加 nodes/edges 时添加颜色。
您在 Graphviz
中绘制彩色节点时指出的 link,而您使用 networkx
进行绘制。您需要指定一个颜色序列并将该值提供给 node_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()
这是一个示例图:
参考文献:
- Color nodes in NetworkX graph