首页 > 解决方案 > networkx 绘制有向图

问题描述

我正在尝试使用networkx库中的加权边创建一个有向图。如图所示的图表是我试图实现的

1 个路由器和 2 个节点的图片,以已知速度进行通信

这是我到目前为止的代码

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

我得到的图片:

结果1

结果2

我很难弄清楚如何启用 X/Y 轴。我不知道不同节点的位置,只知道路由器节点('R')应该放在(0,0)中。此外,我的边缘权重似乎是随机放置的。有时它们放置得很好,有时它们会飞走。最后,定向边缘似乎是直的,而不是如所希望的那样弯曲。我读过应该有一个名为“connectionstyle”的属性,但似乎无法让它工作。

标签: pythonpython-3.xpandasmatplotlibnetworkx

解决方案


问题是弹簧布局适用于更复杂的网络,您不想控制定位。在这种情况下,您想通过设置固定位置来覆盖节点放置算法(我认为),如下所示:

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 默认使用随机起点,这就是每次布局更改的原因)

在此处输入图像描述


推荐阅读