I have a dataset in form of .txt which i want to plot as a graph. This txt provides data as follows:
68 57
65 86
67 83
105 156
etc, so it's an edgelist.
import networkx as nx
import numpy as py
import copy
import matplotlib.pyplot as plt
network0=nx.read_edgelist(r'C:\Users\alexl\Documents\new_python\init_edgelist.txt',create_using=nx.DiGraph)
nx.draw(network0)
plt.show()
After these, i can see a plotted digraph which, as I supposed, has wrong topology. Nodes ans edges are correctly connected, but there is no location information. I tried to import in this another .txt with 3 columns (node x y) for example:
2 478909.145 4204244.629
with this:
coordinates=py.loadtxt(r'C:\Users\alexl\Documents\new_python\nodes_coordinates.txt')
pos=coordinates
nx.draw(network0,pos=pos,with_labels=True)
plt.show()
but doesn't seem to be working.
IndexError: only integers, slices (:
), ellipsis (...
), numpy.newaxis (None
) and integer or boolean arrays are valid indices. <<< That's what it shows in the console when I try to run this.
I suppose it has to do with the fact that coordinates are float?? Or that given by txt they make up a list and we want a dictionary? Afterwards I want to add weights (0,1,2) to the edges but first of all I want to see my data plotted "properly" in terms of topology.
nx.draw expects pos
to be a dictionary when they keys are the nodes and the values are the positions.
Assuming you want to read your input as a numpy array, what you can do is
pos = dict(zip(coordinates[:,0].astype(int), coordinates[:,1:]))
nx.draw(network0, pos=pos, with_labels=True)
Otherwise you could just iterate over the lines of the file and build the dictionary directly.
pos = {}
with open('coords.txt') as f:
for line in f:
node, x, y = line.split()
pos[node] = float(x), float(y)