NetworkX 中的曲线边缘 [英] Curved edges in NetworkX
本文介绍了NetworkX 中的曲线边缘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前为 networkx
图使用以下代码:
将matplotlib.pyplot导入为plt将networkx导入为nxg = nx.Graph()#增加边缘g.add_edge(a", b", weight=0.6)g.add_edge("a","c",权重= 0.2)g.add_edge("c","d",权重= 0.1)g.add_edge("c","e",权重= 0.7)g.add_edge(c", f", weight=0.9)g.add_edge(a", d", weight=0.3)#通过属性"weight"将边缘分组.放大= [(u, v) for (u, v, d) in g.edges(data=True)如果d[重量"]>0.5]esmall = [g.edges中的(u,v,d)的(u,v)(data = True)如果 d[权重"] <= 0.5]# 计算节点的位置pos = nx.circular_layout(g)#绘制图节点nx.draw_networkx_nodes(g, pos, node_size=700)#绘制图形边缘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 =虚线")#注释节点nx.draw_networkx_labels(g, pos, font_size=20, font_family=sans-serif")#图形配置plt.axis(关闭")plt.show()#等待退出
,其具有以下输出:
但我想要的是连接线弯曲而不是直线.我在 matplotlib
中找不到允许我这样做的线条样式.
解决方案
类似于
I currently have the following code for my networkx
graph:
import matplotlib.pyplot as plt
import networkx as nx
g = nx.Graph()
# add edges
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)
# group edges by attribute "weight"
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]
# compute the positions of nodes
pos = nx.circular_layout(g)
# plot the graph nodes
nx.draw_networkx_nodes(g, pos, node_size=700)
# plot the graph 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")
# annotate the nodes
nx.draw_networkx_labels(
g, pos, font_size=20, font_family="sans-serif")
# graphics config
plt.axis("off")
plt.show() # wait before exiting
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.
解决方案
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()
这篇关于NetworkX 中的曲线边缘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文