在 matplotlib 中绘制 Python networkx 图表时出现混乱

2024-01-17

我正在测试如何在“networkx”上创建网络图;我的问题是,当我尝试使用“matplotlib”绘制这些图表时,节点、边缘和标签显得混乱。我希望将标签附加到右侧节点,并且希望边缘看起来像连接节点。

code

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()

image

[1] https://i.stack.imgur.com/Y2Xi6.jpg https://i.stack.imgur.com/Y2Xi6.jpg

我希望我的连接是这样的:

rick james <--> jules caesar
will smith <--> atticus finch
steve miller <--> al capone
...etc

非常感谢任何帮助/见解!


弹簧布局是随机的(随机)。您遇到的一个问题来自这样一个事实:您在不同的时间运行这个随机过程,为节点、边缘和标签生成不同的布局。尝试一下,一次性计算布局:

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)

我不会声称这会给你一个“好的”布局,因为它不会(至少在我的机器上):

Maybe a networkx.draw_circular https://networkx.github.io/documentation/latest/reference/generated/networkx.drawing.nx_pylab.draw_circular.html#networkx.drawing.nx_pylab.draw_circular布局会更合适:

nx.draw_circular(g)

您可以阅读有关所有 NetworkX 布局的信息here https://networkx.github.io/documentation/latest/reference/drawing.html,包括 Graphviz(如 @ThomasHobohm 所建议)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 matplotlib 中绘制 Python networkx 图表时出现混乱 的相关文章

随机推荐