python - 请问如何在python中绘制多重图?我尝试使用networkx库这样做,但只绘制了两个节点之间的一个连接
问题描述
请问如何在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()
这是结果:
推荐阅读
- javascript - 如何扩展已经在使用的 React 组件?
- microsoft-graph-api - Access to Microsoft eDiscovery with Microsoft Graph API
- java - 忽略正则表达式的字符串过滤器
- python - QSplitter、QWidget 调整大小、setSizes()、setStretchFactor() 和 sizeHint() - 如何让它们一起工作?
- python - OpenAI "gym" Library throws a NoneType error on env.render()
- python - Is there a way for pytest to check if a log entry was made at Error level or higher?
- python - 正则表达式替换元素,除非在同一行和匹配之前有另一个匹配
- python - genfromtext() numpy function for reading weight csv files doesn't work in Jupyter (Face Recognition DL assignment )
- optimization - 以快进方式播放模拟
- node.js - 如何让 AWS S3 存储桶中的 Angular 应用程序对 AWS Elastic Beanstalk 中的服务进行 API 调用