简体   繁体   English

使用networkx从矩阵到图(有向和无向)

[英]From Matrix to Graph (directed and undirected) using networkx

Starting from the following bumpy matrix I would like to create a graph using the python library Networkx从以下颠簸矩阵开始,我想使用 python 库 Networkx 创建一个图形

matrix([[0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [2, 0, 0, 0, 0, 0, 0, 1],
        [0, 0, 0, 0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0, 0, 2, 1],
        [0, 0, 0, 1, 0, 0, 2, 0],
        [2, 2, 0, 0, 0, 0, 0, 0],
        [0, 0, 1, 0, 1, 0, 0, 0]])

Where:在哪里:

  • 0 means that the node is NOT connected to another node 0 表示该节点未连接到另一个节点
  • 1 means that the node is connected to another node 1 表示该节点连接到另一个节点
  • 2 means that the node has an outgoing arrow to another node (eg, 1 --> 6) 2 表示该节点有一个指向另一个节点的传出箭头(例如,1 --> 6)

The problem is that I'm able to draw directed or undirected graph, but not a mix of both.问题是我能够绘制有向图或无向图,但不能同时绘制两者。

Thanks for your help谢谢你的帮助

#libraries
import networkx as nx
import numpy as np

#input
X = np.array([[0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [2, 0, 0, 0, 0, 0, 0, 1],
        [0, 0, 0, 0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0, 0, 2, 1],
        [0, 0, 0, 1, 0, 0, 2, 0],
        [2, 2, 0, 0, 0, 0, 0, 0],
        [0, 0, 1, 0, 1, 0, 0, 0]])


G = nx.DiGraph(X>0)
nx.draw_kamada_kawai(G, with_labels=True)

图形

In this way you have that undirected edges are bidirectional connection.这样你就有了无向边是双向连接的。 I think there is not another way to implement your graph in networkx because the mixed graph are not allowed, as mentioned here:我认为没有其他方法可以在networkx中实现您的图,因为不允许使用混合图,如此处所述:

- Is it possible to add undirected and directed edges to a graph object in networkx - 是否可以将无向和有向边添加到 networkx 中的图形对象

- MixedGraph and MixedMultiGraph - MixedGraph 和 MixedMultiGraph

The only other solution I can imagine is to build a directed graph and separately an undirected graph, but it obliviously depends on what is your goal and on what the graph is to be used for.我能想象的唯一其他解决方案是构建有向图和单独的无向图,但这完全取决于您的目标是什么以及该图的用途。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM