[英]networkx - how to show edge labels in exported Graphviz
請告知如何在 Graphviz 中顯示邊緣標簽。
嘗試在 NetworkX 生成的 Graphviz 中顯示邊緣標簽。
在 NetworkX 中,它顯示邊緣標簽。
import matplotlib.pyplot as plt
import networkx as nx
MDG = nx.MultiDiGraph()
# --------------------------------------------------------------------------------
# Forward edges
# --------------------------------------------------------------------------------
forward_edges = [
("sushi/0", "goes/1"),
("sushi/0", "with/2"),
("sushi/0", "wasabi/3"),
("goes/1", "with/2"),
("goes/1", "wasabi/3"),
("with/2", "wasabi/3"),
]
MDG.add_edges_from(
forward_edges,
edge_color='b',
weight='length',
length=100,
)
# layout definition must come after adding all nodes/edges.
# Otherwise Node X has no position error.
pos=nx.spring_layout(MDG,seed=5, weight='length')
fig, ax = plt.subplots(figsize=(10, 5))
# --------------------------------------------------------------------------------
# Draw nodes & labels
# --------------------------------------------------------------------------------
nx.draw_networkx_nodes(
MDG,
pos,
ax=ax,
node_size=500,
node_color="cyan",
)
nx.draw_networkx_labels(
MDG,
pos,
ax=ax,
font_weight='bold',
font_size=12,
)
# --------------------------------------------------------------------------------
# Draw forward edges
# --------------------------------------------------------------------------------
nx.draw_networkx_edges(
MDG,
pos,
ax=ax,
edgelist=forward_edges,
edge_color="b",
arrowsize=20,
arrowstyle="->",
connectionstyle='arc3, rad=0.1',
)
nx.draw_networkx_edge_labels(
MDG,
pos,
label_pos=0.2,
edge_labels={
("sushi/0", "goes/1"): 0.3,
("sushi/0", "with/2"): 0.1,
("sushi/0", "wasabi/3"): 0.6,
("goes/1", "with/2"): 0.75,
("goes/1", "wasabi/3"): 0.75,
("with/2", "wasabi/3"): 0.75,
},
font_color='b'
)
nx.set_edge_attributes(
G=MDG,
values={
("sushi/0", "goes/1", 0.1): {"label": 0.1},
("sushi/0", "with/2", 0.1): {"label": 0.2},
("sushi/0", "wasabi/3", 0.6): {"label": 0.6},
("goes/1", "with/2", 0.1): {"label": 0.1},
("goes/1", "wasabi/3", 0.75): {"label": 0.75},
("with/2", "wasabi/3", 0.75): {"label": 0.75},
}
)
但是,Graphviz 沒有顯示它們。
D = nx.drawing.nx_agraph.to_agraph(MDG)
# Modify node fillcolor and edge color.
D.node_attr.update(color='blue', style='filled', fillcolor='yellow')
D.edge_attr.update(color='blue', arrowsize=1)
D.layout('dot')
D.draw('MDG.png')
您沒有將標簽值正確傳遞到邊緣:
nx.set_edge_attributes(
MDG,
values={
("sushi/0", "goes/1",0): 0.1,
("sushi/0", "with/2",0):0.2,
("sushi/0", "wasabi/3",0) :0.6,
("goes/1", "with/2",0): 0.1,
("goes/1", "wasabi/3",0):0.75,
("with/2", "wasabi/3",0):0.75,
},
name = "label"
)
您需要將值作為字典傳遞,鍵為(start_node, end_node, edge_key)
。 由於您使用的是 MultiDiGraph,因此每條邊都有一個鍵,可以使其與具有相同開始和結束節點的其他邊區分開來。
您可以檢查邊緣鍵:
for e in MDG.edges(keys=True):
print(e)
因為在您的情況下,每個節點對沒有多個邊,所有鍵都為零。
生成 pygrphviz 產生:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.