Curved edges in NetworkX

拟墨画扇 提交于 2020-12-12 04:38:13

问题


I currently have the following code for my networkx graph:

import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()

G.add_edge("a", "b", weight=0.6)
G.add_edge("a", "c", weight=0.2)
G.add_edge("c", "d", weight=0.1)
G.add_edge("c", "e", weight=0.7)
G.add_edge("c", "f", weight=0.9)
G.add_edge("a", "d", weight=0.3)

elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] > 0.5]
esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] <= 0.5]

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

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

# edges
nx.draw_networkx_edges(G, pos, edgelist=elarge, width=6)
nx.draw_networkx_edges(
    G, pos, edgelist=esmall, width=6, alpha=0.5, edge_color="b", style="dashed"
)

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

plt.axis("off")
plt.show()

Which has the following output:

But what I want is for the connecting lines to be curved not straight. I couldn't find a line style in matplotlib that allows me to do that.


回答1:


Similarly to this answer, you could do:

plt.figure(figsize=(15,8))

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

ax = plt.gca()

for edge in G.edges():
    source, target = edge
    rad = 0.2
    c = edge in elarge
    arrowprops=dict(arrowstyle="-", 
                    color='black' if c else 'blue',
                    connectionstyle=f"arc3,rad={rad}",
                    linestyle= '-' if c else '--',
                    alpha=0.6,
                    linewidth=5)
    ax.annotate("",
                xy=pos[source],
                xytext=pos[target],
                arrowprops=arrowprops
               )
# nodes
nx.draw_networkx_nodes(G, pos, node_size=700, node_color='black')
# labels
nx.draw_networkx_labels(G, pos, font_size=20, 
                        font_family="sans-serif", 
                        font_color ='white')

plt.box(False)
plt.show()



来源:https://stackoverflow.com/questions/63918432/curved-edges-in-networkx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!