You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用write_dot为DiGraph绘制边权重?

如何用write_dot为NetworkX有向图展示边权重

Hey there! Let's get your directed graph displaying edge weights properly with write_dot. First, let's fix up your existing code and walk through exactly how to make this work.

先修正原代码的小问题

Your original code has a tiny bug when adding nodes: the line G.add_node(nodes) inside the loop adds the same node (equal to your input node count) repeatedly. Instead, we can either add nodes correctly, or skip manual node creation entirely—since add_weighted_edges_from automatically creates nodes that appear in edges.

修改后的完整代码

Here's the adjusted code that properly stores edge weights and ensures write_dot includes them as labels:

import networkx as nx
from networkx.drawing.nx_agraph import write_dot

# Initialize directed graph
G = nx.DiGraph()

# Optional: Add all nodes manually (ensures nodes with no edges are included)
node_count = int(input("Enter a number of nodes: "))
for i in range(node_count):
    G.add_node(i)

# Collect weighted edges
transitions = []
transition_count = int(input("Enter a number of transitions: "))
for _ in range(transition_count):
    frm = int(input("Enter from node: "))
    to = int(input("Enter to node: "))
    weight = int(input("Enter edge weight: "))
    transitions.append((frm, to, weight))

# Add edges with weight attribute
G.add_weighted_edges_from(transitions)

# Critical step: Set edge label to the weight (so write_dot renders it)
for u, v, edge_data in G.edges(data=True):
    edge_data['label'] = edge_data['weight']

# Save the graph to a DOT file
write_dot(G, 'weighted_digraph.dot')
print("Success! DOT file saved as weighted_digraph.dot")

关键说明

  • When you use add_weighted_edges_from, NetworkX automatically stores the weight in each edge's 'weight' attribute. However, write_dot doesn't use this as the display label by default—so we explicitly set the 'label' attribute to the weight value.
  • Alternatively, you can set the label directly when adding edges to skip the loop later:
    # Replace the add_weighted_edges_from line with this
    for frm, to, weight in transitions:
        G.add_edge(frm, to, weight=weight, label=weight)
    

渲染DOT文件为图片

To turn the saved .dot file into a visual graph with weights, use Graphviz's dot command (you'll need Graphviz installed on your system):

dot -Tpng weighted_digraph.dot -o weighted_digraph.png

This will generate a PNG image where each edge shows its corresponding weight.

内容的提问来源于stack exchange,提问作者Bauka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:18:26