请问如何在python中绘制多图?我尝试使用 networkx 库这样做,但只绘制了两个节点之间的一个连接

Please How to draw multigraphs in python? I tried it do so using networkx libraries but only one connection between two nodes is drawn

请问如何在python中绘制多图? 我尝试使用 networkx 库这样做,但只绘制了两个节点之间的一个连接

如果你这样做,它应该允许你在相同节点之间绘制多条边。但是,绘制时它们会重叠,因为它们被绘制为直线。

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

graph = nx.MultiGraph() # Must use MultiGraph rather than Graph

graph.add_nodes_from(['A', 'B', 'C', 'D', 'E'])
print('There are {} nodes in the graph: {}'.format(graph.number_of_nodes(), 
graph.nodes()))

graph.add_edges_from([('A', 'C'), 
                      ('A', 'B'), 
                      ('A', 'E'),
                      ('B', 'E'),
                      ('B', 'D'),
                      ('C', 'A')])
print('There are {} edges in the graph: {}'.format(graph.number_of_edges(), 
graph.edges()))

nx.draw(graph, with_labels = True, font_weight='bold')
plt.show()

# Confirms two edges between A and C
print(graph.number_of_edges('A', 'C'))

这将允许您在节点之间的多条边上存储属性。我还没有看到任何纯 networkx 选项可以让您单独可视化这些行。

您可以使用 GraphViz 执行此操作:

这是文档:https://graphviz.readthedocs.io/en/stable/index.html

您可以使用 pip 安装:

pip install graphviz

然后您必须安装可执行文件。我在 Mac 上使用了自制软件,所以我简单地输入:

brew install graphviz

下面是两个节点相互指向的基本示例:

from graphviz import Digraph

g = Digraph()

nodes = ['A', 'B', 'C']
edges = [['A', 'B'],['B', 'C'],['B', 'A']]

for node in nodes:
    g.node(node)

for edge in edges:
    start_node = edge[0]
    end_node = edge[1]
    g.edge(start_node, end_node)

g.view()

这是结果: