networkx 绘制有向图

networkx plotting directed graph

我正在尝试使用来自 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-axis。我不知道不同节点的位置,只知道路由器节点('R')应该放在(0,0)。此外,我的边缘权重似乎是随机放置的。有时它们放置得很好,有时它们会飞走。最后,有向边似乎是直的,而不是像希望的那样弯曲。我读过应该有一个名为 'connectionstyle' 的属性,但似乎无法使其正常工作。

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

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 字典,您现在可以将事物准确地放置在您想要的位置,并且它们不会每次都改变(spring 默认情况下使用随机起点,这就是布局每次改变的原因时间)