Python networkx图在matplotlib绘制时显示混乱
我正在尝试使用“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()
图片
[1] https://i.stack.imgur.com/Y2Xi6.jpg
我希望我的连接能像这样:
rick james <--> jules caesar
will smith <--> atticus finch
steve miller <--> al capone
...etc
任何帮助或建议都非常感谢!
2 个回答
1
Matplotlib在画出清晰易读的图表方面表现得不太好。我建议你使用Graphviz,因为它和NetworkX可以直接配合使用,而且它让你可以调整更多的设置,使用起来更灵活。
2
这个弹簧布局是随机的。你遇到的问题是因为你在不同的时间运行这个随机过程,导致节点、边和标签的布局每次都不一样。试试这样,只计算一次布局:
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布局,包括Graphviz(正如@ThomasHobohm所建议的)。