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

问题描述

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

标签: pythongraph-theory

解决方案


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

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()

这是结果:

在此处输入图像描述


推荐阅读