我正在测试如何在“networkx”上创建网络图;我的问题是,当我尝试使用“matplotlib”绘制这些图形时,节点、边和标签显得困惑。我想将标签附加到右节点,并且我希望边缘看起来像是连接节点。
代码
import networkx as nx
try:
import matplotlib.pyplot as plt
except:
raise
g = nx.MultiGraph()
strList = ["rick james", "will smith", "steve miller", "rackem willie", "little tunechi", "ben franklin"]
strList2 = ["jules caesar", "atticus finch", "al capone", "abe lincoln", "walt white", "doc seuss"]
i = 0
while i < len(strList) :
g.add_edge(strList[i], strList2[i])
i = i + 1
nx.draw_networkx_nodes(g,pos = nx.spring_layout(g), nodelist = g.nodes())
nx.draw_networkx_edges(g,pos = nx.spring_layout(g), edgelist = g.edges())
nx.draw_networkx_labels(g,pos=nx.spring_layout(g))
#plt.savefig("testImage.png")
plt.show()
图片
我希望我的连接是这样的:
rick james <--> jules caesar
will smith <--> atticus finch
steve miller <--> al capone
...etc
非常感谢任何帮助/见解!
请您参考如下方法:
Spring 布局是随机的(random)。您遇到的一个问题是您在不同的时间运行此随机过程——为节点、边和标签生成不同的布局。试试这个,你计算一次布局:
pos = nx.spring_layout(g)
nx.draw_networkx_nodes(g, pos=pos, nodelist = g.nodes())
nx.draw_networkx_edges(g, pos=pos, edgelist = g.edges())
nx.draw_networkx_labels(g, pos=pos)
或者在您不需要为单个节点/边/标签设置样式的情况下:
nx.draw_spring(g)
我不会声称这会给你一个“好的”布局,因为它不会(至少在我的机器上):
也许是 networkx.draw_circular布局会更合适:
nx.draw_circular(g)
您可以阅读有关所有 NetworkX 布局的信息 here ,包括 Graphviz(如@ThomasHobohm 所建议)。
