添加具有颜色属性的边/节点 [英] Adding an edge/node with a color attribute
问题描述
我使用Python的networkx
包.文档说我们可以执行H.add_edge(1,2,color='blue')
,但是输出显示的是带有默认(黑色)颜色的边缘.当我执行H.add_node(12,color='green')
时,会得到一个具有相同默认红色的新节点.
I a using the networkx
package of Python. The documentation says we can do H.add_edge(1,2,color='blue')
but the output shows an edge with the default (black) color. When I do H.add_node(12,color='green')
I get a new node with same default red color.
推荐答案
Peter要更改绘制的颜色,请提供
Peter, according to the documentation, to change the color with which nodes/edges are drawn, you have to provide the node_color
argument to the drawing function. I.e. from this example, to draw a graph like this (note different colors of nodes):
代码是:
#!/usr/bin/env python
"""
Draw a graph with matplotlib.
You must have matplotlib for this to work.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
try:
import matplotlib.pyplot as plt
except:
raise
import networkx as nx
G=nx.house_graph()
# explicitly set positions
pos={0:(0,0),
1:(1,0),
2:(0,1),
3:(1,1),
4:(0.5,2.0)}
nx.draw_networkx_nodes(G,pos,node_size=2000,nodelist=[4])
nx.draw_networkx_nodes(G,pos,node_size=3000,nodelist=[0,1,2,3],node_color='b')
nx.draw_networkx_edges(G,pos,alpha=0.5,width=6)
plt.axis('off')
plt.savefig("house_with_colors.png") # save as png
plt.show() # display
请注意第二次调用draw_networkx_nodes
的node_color
参数.这有帮助吗?
Note the node_color
argument to the second call to draw_networkx_nodes
. Does this help?
这篇关于添加具有颜色属性的边/节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!