如何在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()

直边来自 nx.draw_networkx_edges() 调用.如果删除它们,则仅留下弯曲的边缘,但是它们没有指定的边缘权重.您可以如下更新for循环,以获取具有边缘权重的弯曲边缘.

The straight edges come from the nx.draw_networkx_edges() calls. If you remove them, you are left with just the curved edges, but they don't have the specified edge weights. You can update the for loop as below to get the curved edges with edge weights.

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 参数根据权重"设置线宽.图中的边属性.如果这不是您想要的,可以将其设置为某个默认值或将其删除.

The lw parameter sets the line width based on the "weight" edge attribute from the graph. If that's not what you want you can set it to some default value or remove it.