Python: Graph a Network from Data -
i have following dataset:
firm_id_1 firm_id_2 1 2 1 4 1 5 2 1 2 3 3 2 3 6 4 1 4 5 4 6 5 4 5 7 6 3 .... i graph network of firm_id = 1. in other words, want see graph shows firm_id = 1 directly connected 2, 4, 5, , indirectly connected 3 via firm 2, connected 6 via firm 4 , indirectly connected 7 via firm 5. in other words graph shortest distance each node (firm_id) starting firm_id=1. there 3000 nodes in data , know firm 1 reaches nodes in less 9 vertices. how can graph in python?
i start library called networkx. i'm not sure understand looking for, think should close enough modify it.
this program load data in text file graphdata.txt, split whitespace, , add pair edge.
it calculate shortest paths nodes 1, , print if distance larger 9... see documentation more details.
lastly, render graph using spring layout file called mynetwork.png , screen.
some optimization may / may not needed 3000 nodes.
hope helps!
import networkx nx import matplotlib.pyplot plt graph = nx.graph() open('graphdata.txt') f: line in f: firm_id_1, firm_id_2 = line.split() graph.add_edge(firm_id_1, firm_id_2) paths_from_1 = nx.shortest_path(graph, "1") path in paths_from_1: if len(paths_from_1[node]) > 9: print "shortest path 1 to", node, "is longer 9" pos = nx.spring_layout(graph, iterations=200) nx.draw(graph, pos) plt.savefig("mynetwork.png") plt.show()
Comments
Post a Comment