web-dev-qa-db-fra.com

Tracer le graphique NetworkX à partir de la matrice d'adjacence dans un fichier CSV

Je me bats avec ce problème depuis un petit moment maintenant, je sais que c'est très simple - mais j'ai peu d'expérience avec Python ou NetworkX. Ma question est très simple, j'essaie de tracer un grand ensemble de données (environ 200 lignes/colonnes) d'une matrice qui ressemble à ceci. La première ligne et la première colonne sont identiques.

  A,B,C,D,E,F,G,H,I,J,K
A,0,1,1,0,1,1,1,1,0,1,0
B,1,0,0,0,1,1,1,1,0,1,0
C,1,0,0,0,1,1,1,1,0,1,0

C'est juste une matrice montrant comment les gens sont connectés, et tout ce que je veux, c'est importer et tracer ce fichier csv, avec ses étiquettes correspondantes dans NetworkX.

J'ai ce fichier (people.csv), et en regardant les réponses précédentes ici , il semble que la meilleure façon de le faire est de placer les données dans un tableau avec numpy.

Il semble y avoir un problème avec ceci:

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

mydata = genfromtxt('mouse.csv', delimiter=',')

J'obtiens la sortie suivante:

File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/lib/npyio.py", line 1272, in genfromtxt
  fhd = iter(np.lib._datasource.open(fname, 'rbU'))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/lib/_datasource.py", line 145, in open
  return ds.open(path, mode)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/lib/_datasource.py", line 472, in open
  found = self._findfile(path)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/lib/_datasource.py", line 323, in _findfile
  if self.exists(name):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/lib/_datasource.py", line 417, in exists
  from urllib2 import urlopen
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 94, in <module>
  import httplib
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 69, in <module>
  from array import array
      File "/Users/Plosslab/Documents/PythonStuff/array.py", line 4, in <module>
      NameError: name 'array' is not defined
16
Workhorse

J'ai fait un petit csv appelé mycsv.csv qui a ce qui suit:

,a,b,c,d
a,0,1,0,1
b,1,0,1,0
c,0,1,0,1
d,1,0,1,0

Vous n'avez pas de "," comme premier caractère sur la première ligne, mais à la place, vous avez un espace, donc si c'est une erreur de ma part, faites le moi savoir. L'idée générale sera la même. Lire dans le csv comme tel:

from numpy import genfromtxt
import numpy as np
mydata = genfromtxt('mycsv.csv', delimiter=',')
print(mydata)
print(type(mydata))

Cela imprime:

[[ nan  nan  nan  nan  nan]
 [ nan   0.   1.   0.   1.]
 [ nan   1.   0.   1.   0.]
 [ nan   0.   1.   0.   1.]
 [ nan   1.   0.   1.   0.]]
<type 'numpy.ndarray'>

Maintenant que nous avons le csv lu comme un tableau numpy, nous devons extraire juste la matrice d'adjacence:

adjacency = mydata[1:,1:]
print(adjacency)

Cela imprime:

[[ 0.  1.  0.  1.]
 [ 1.  0.  1.  0.]
 [ 0.  1.  0.  1.]
 [ 1.  0.  1.  0.]]

Vous pouvez simplement découper votre tableau numpy selon vos besoins si mon petit exemple n'est pas exactement le vôtre.

Pour tracer le graphique, vous devrez importer matplotlib et networkx:

import matplotlib.pyplot as plt
import networkx as nx

def show_graph_with_labels(adjacency_matrix, mylabels):
    rows, cols = np.where(adjacency_matrix == 1)
    edges = Zip(rows.tolist(), cols.tolist())
    gr = nx.Graph()
    gr.add_edges_from(edges)
    nx.draw(gr, node_size=500, labels=mylabels, with_labels=True)
    plt.show()

show_graph_with_labels(adjacency, make_label_dict(get_labels('mycsv.csv')))

Voici un court tutoriel sur les graphiques avec python.

graph from csv

22
Scott

Cela peut être fait facilement en utilisant pandas et networkx.

Par exemple, j'ai créé un petit fichier csv appelé test.csv as

A,B,C,D,E,F,G,H,I,J,K
A,0,1,1,0,1,1,1,1,0,1,0
B,1,0,0,0,1,1,1,1,0,1,0
C,1,0,0,0,1,1,1,1,0,1,0
D,0,0,0,0,1,0,1,1,0,1,0
E,1,0,0,0,1,1,1,1,0,1,0
F,0,0,1,0,1,0,0,0,0,1,0
G,1,0,0,0,0,0,0,1,0,0,0
H,1,0,0,0,1,1,1,0,0,1,0
I,0,0,0,1,0,0,0,0,0,0,0
J,1,0,0,0,1,1,1,1,0,1,0
K,1,0,0,0,1,0,1,0,0,1,0

Vous pouvez lire ce fichier csv et créer un graphique comme suit

import pandas as pd
import networkx as nx
input_data = pd.read_csv('test.csv', index_col=0)
G = nx.DiGraph(input_data.values)

Pour tracer ce graphique, utilisez

nx.draw(G)

Vous obtiendriez une intrigue similaire à celle-ci.

Output of <code>nx.draw(G)</code>

14
Abinash Panda