NetworkX:绘图图

时间:2015-03-20 00:00:58

标签: python graph networkx

我正在尝试使用Python中的NetworkX绘制图形。我使用以下代码:

G=nx.to_networkx_graph(adj)
pos=nx.spring_layout(G)

#G=nx.path_graph(8)
nx.draw(G,pos,labels)
plt.savefig("simple_path.png") # save as png
plt.show() # display

我得到了这个输出:

a busy cat

但我想用标签获得以下输出:

a busy cat

我可以对代码做什么?谢谢。

1 个答案:

答案 0 :(得分:2)

因此,对于定位,您已根据pos设置spring_layoutpos给出节点的位置。检查一下 - 一旦你定义了它,请让python为你打印pos,看看它在做什么。

这是一个替代代码:

import networkx as nx
import pylab as py
blue_edges = [('B', 'C'), ('B', 'D'), ('B', 'E'), ('E', 'F')]
red_edges = [('A', 'B'), ('A', 'C'), ('C', 'E'), ('D', 'E'), ('D', 'F')]

G=nx.Graph() #define G
G.add_edges_from(blue_edges)
G.add_edges_from(red_edges)

pos = {'A':(0,0), 'B':(1,1), 'C':(1,-1), 'D':(2,1), 'E':(2,-1), 'F':(3,0)}

nx.draw_networkx(G, pos=pos, edgelist = [], node_color = 'k')
nx.draw_networkx(G, pos=pos, nodelist = [], edgelist = blue_edges, edge_color = 'b')
nx.draw_networkx(G, pos=pos, nodelist = [], edgelist = red_edges, edge_color = 'r')

enter image description here

如果您想要它而不显示x和y轴,请将最后一位更改为:

nx.draw(G, pos=pos, edgelist = [], node_color = 'k')
nx.draw(G, pos=pos, nodelist = [], edgelist = blue_edges, edge_color = 'b')
nx.draw(G, pos=pos, nodelist = [], edgelist = red_edges, edge_color = 'r')

enter image description here