代码之家  ›  专栏  ›  技术社区  ›  alexey

为什么Networkx中的图形将箭头指向错误的方向?

  •  0
  • alexey  · 技术社区  · 1 年前

    我有一个pandas数据框架,有两列:源和汇。在简化形式中,只有5个用户(源列)可以欠任何其他用户(汇列)的钱。 我认为以下代码将显示用户1的图,因为用户3(是箭头正确,良好),用户2到4(良好),3到5(良好)、4到1(错误)、5到2(错误)。我该怎么做才能让最后两个箭头指向正确的方向?

    output of the sample code

    df = pd.DataFrame({'source': [1, 2, 3, 4, 5], 'sink': [3, 4, 5, 1, 2]})
    
    G = nx.Graph()
    for row in df.iterrows():
        print(row[1]['source'], row[1]['sink'])
        G.add_edge(row[1]['source'], row[1]['sink'])
    # nx.draw(G, with_labels=True, font_weight='bold')
    
    pos = nx.spring_layout(G)
    nodes = nx.draw_networkx_nodes(G, pos, node_color="orange")
    nx.draw_networkx_labels(G, pos)
    edges = nx.draw_networkx_edges(
        G,
        pos,
        arrows=True,
        arrowstyle="->",
        arrowsize=10,
        width=2,
    )
    
    1 回复  |  直到 1 年前
        1
  •  1
  •   Timeless    1 年前

    这是因为 秩序 数据帧中的用户。如果你仔细看你的图表,箭头总是指向 U V 哪里 U < V ( 就身体位置而言 ). 实际上,networkx使用 FancyArrowPatch(start, end, ...) 在引擎盖下制作箭头,如本例所示:

    import matplotlib.pyplot as plt
    from matplotlib.patches import FancyArrowPatch
    
    fig, ax = plt.subplots(figsize=(6, 1))
    
    ax.add_patch(
        FancyArrowPatch((0.2, 0.5), (0.8, 0.5), mutation_scale=30, arrowstyle="-|>")
    )
    

    enter image description here

    你想要的是 DiGraph ,箭头应该与之配合使用:

    DG = nx.from_pandas_edgelist(df, "source", "sink", create_using=nx.DiGraph)
    
    nx.draw_networkx(
        DG,
        nx.spring_layout(DG, seed=0),
        node_color="orange",
        edgecolors="k",
        arrowsize=20,
    )
    

    enter image description here