python - networkx 绘制有向图
问题描述
我正在尝试使用networkx库中的加权边创建一个有向图。如图所示的图表是我试图实现的
这是我到目前为止的代码
import networkx as nx
import matplotlib.pyplot as plt
import pandas as panda
df = panda.DataFrame({'from':['R','R','D04','D04','D06','D06'], 'to':['D04','D06','R','D06','R','D04']})
G=nx.from_pandas_edgelist(df, 'from', 'to', create_using=nx.DiGraph())
G['R']['D04']['weight'] = 243.0
G['R']['D06']['weight'] = 150.0
G['D06']['D04']['weight'] = 211.0
pos = nx.spring_layout(G)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos, edge_labels=labels)
# Make the graph
nx.draw(G, with_labels=True, node_size=1500, alpha=0.3, font_weight="bold", arrows=True)
plt.axis('on')
plt.show()
我得到的图片:
我很难弄清楚如何启用 X/Y 轴。我不知道不同节点的位置,只知道路由器节点('R')应该放在(0,0)中。此外,我的边缘权重似乎是随机放置的。有时它们放置得很好,有时它们会飞走。最后,定向边缘似乎是直的,而不是如所希望的那样弯曲。我读过应该有一个名为“connectionstyle”的属性,但似乎无法让它工作。
解决方案
问题是弹簧布局适用于更复杂的网络,您不想控制定位。在这种情况下,您想通过设置固定位置来覆盖节点放置算法(我认为),如下所示:
import networkx as nx
import matplotlib.pyplot as plt
import pandas as panda
df = panda.DataFrame({'from':['R','R','D04','D04','D06','D06'], 'to':['D04','D06','R','D06','R','D04']})
G=nx.from_pandas_edgelist(df, 'from', 'to', create_using=nx.DiGraph())
G['R']['D04']['weight'] = 243.0
G['R']['D06']['weight'] = 150.0
G['D06']['D04']['weight'] = 211.0
#pos = nx.spring_layout(G)
#instead of spring, set the positions yourself
labelPosDict = {'R':[0.1,0.3], 'D04':[0.5,.9], 'D06':[.9,.18]}
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos=labelPosDict, edge_labels=labels)
plt.axvline(.1, alpha=0.1, color='green')
plt.axhline(.3, alpha=0.1, color='green')
#Create a dict of fixed node positions
nodePosDict = {'R':[0.1,0.3], 'D04':[0.5,.9], 'D06':[.9,.18]}
# Make the graph - add the pos and connectionstyle arguments
nx.draw(G, k=5,with_labels=True, pos=nodePosDict,
node_size=1500, alpha=0.3, font_weight="bold", arrows=True,
connectionstyle='arc3, rad = 0.1')
plt.axis('on')
plt.show()
通过控制 pos dict,您现在可以将东西准确地放置在您想要的位置,并且它们不会每次都更改(spring 默认使用随机起点,这就是每次布局更改的原因)
推荐阅读
- python - 在 matplotlib 3D 中标记第一个和最后一个数据点
- javascript - Javascript 提示显示为未定义
- python - 编译 cython 生成的 c 代码时出错:针对 `.rodata.str1.1' 重定位 R_X86_64_32
- zapier - 在 Zapier CLI 应用程序上连接多个帐户
- javascript - 如何在JS中从数组中切出值
- spring - Spring Boot Hibernate 自动配置与手动注释配置
- c# - 用于否定字符类的 C# 正则表达式,除非字符彼此相邻
- javascript - 用于显示十六进制数字的控制台设置
- c# - 无法通过脚本更改导入的搅拌机对象材质颜色
- r - 在r中制作求和函数