如何在 Networkx 图上添加箭头

How to add arrows on Networkx graph

我用 Python 中的 networkx 库制作了一个图表。 现在我想在图表的线条上添加箭头,但看起来我做错了什么。这是我的代码:

import networkx as nx

analysis_graph = nx.Graph()
# I have also tried with DiGraph() but it still does not work

node_list = ["A", "B", "C", "D", "E", "F"]

analysis_graph.add_nodes_from(node_list)
#print(analysis_graph.nodes())

nx.draw(analysis_graph, with_labels = True)
relation_list = [['A', 'B'],
                 ['A', 'C'],
                 ['B', 'D'],
                 ['C', 'E'],
                 ['D', 'F'],
                 ['E', 'D'],
                 ['C', 'E'],
                 ['B', 'D'],                 
                 ['C', 'F'],
                 ['A', 'E'],
                 ['B', 'C'],                 
                 ['B', 'F'],
                 ['D', 'A']]

analysis_graph = nx.from_edgelist(relation_list)
print(nx.info(analysis_graph))
nx.draw(analysis_graph, with_labels = True, arrowsize=20, arrowstyle='fancy')

我做错了什么?

要绘制箭头,图形显然必须是 DiGraph 对象。 如果我更改以下行:

analysis_graph = nx.from_edgelist(relation_list)

analysis_graph = nx.from_edgelist(relation_list, create_using=nx.DiGraph)

我确实得到了想要的输出。

您之前在第 2 行中尝试实例化 DiGraph 对象(忽略空格)

analysis_graph = nx.DiGraph()

没有效果,因为您在调用 nx.from_edgelist 时覆盖了 analysis_graph 对象。你可能想写的是

analysis_graph = nx.DiGraph()
analysis_graph.add_nodes_from(nodelist)
analysis_graph.add_edges_from(relation_list)