如何在networkX图中弯曲边缘

问题描述 投票:0回答:1

我之前曾问过这个问题,关于如何在networkX中实现弯曲边缘。它与我之前的数据配合得很好,但是当我更新数据和代码时,我不确定哪里出了问题。边缘仅对某些节点弯曲,并且实际上添加了两次连接。我不知道为什么它要绘制两次边缘,一次是直线,一次是弯曲的。

我的代码:

import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()

G.add_edge("Ted", "May", weight=0.5)
G.add_edge("Ted", "Ray", weight=1)
G.add_edge("Ted", "Chris", weight=1)
G.add_edge("Ted", "Sam", weight=3)
G.add_edge("Ted", "April", weight=1)
G.add_edge("Ted", "Ana", weight=0)


G.add_edge("Ana", "Ryan", weight=1)
G.add_edge("Ana", "Jim", weight=0.5)
G.add_edge("Ana", "Ben", weight=1)


for0 = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] == 0]
for05 = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] == 0.5]
for1 = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] == 1]
for15 = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] == 1.5]
for3 = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] == 3]



pos = nx.circular_layout(G)  # positions for all nodes
ax=plt.gca()

# nodes
sc = nx.draw_networkx_nodes(G, pos, node_size=700)

# edges


nx.draw_networkx_edges(G, pos, edgelist=for0, width=0)
nx.draw_networkx_edges(G, pos, edgelist=for05, width=0.5)

nx.draw_networkx_edges(G, pos, edgelist=for1, width=1)
nx.draw_networkx_edges(G, pos, edgelist=for15, width=1.5)

nx.draw_networkx_edges(G, pos, edgelist=for3, width=3)

for edge in G.edges():
    source, target = edge
    rad = 0.2
    arrowprops=dict(arrowstyle="-",
                    color='blue',
                    connectionstyle=f"arc3,rad={rad}",
                    linestyle= '-',
                    alpha=0.6,)
    ax.annotate("",
                xy=pos[source],
                xytext=pos[target],
                arrowprops=arrowprops
               )

# labels
nx.draw_networkx_labels(G, pos, font_size=20, font_family="sans-serif")


plt.show()
python matplotlib networkx edges
1个回答
3
投票

直边来自

nx.draw_networkx_edges()
调用。如果删除它们,则只剩下弯曲的边缘,但它们没有指定的边缘权重。您可以如下更新 for 循环以获得具有边缘权重的弯曲边缘。

for edge in G.edges():
    source, target = edge
    rad = 0.2
    arrowprops=dict(lw=G.edges[(source,target)]['weight'],
                    arrowstyle="-",
                    color='blue',
                    connectionstyle=f"arc3,rad={rad}",
                    linestyle= '-',
                    alpha=0.6)
    ax.annotate("",
                xy=pos[source],
                xytext=pos[target],
                arrowprops=arrowprops
               )

lw
参数根据图表中的“权重”边缘属性设置线宽。如果这不是您想要的,您可以将其设置为某个默认值或将其删除。

© www.soinside.com 2019 - 2024. All rights reserved.