In: Computer Science
Using Python and networkx library, choose two graphs (one with a small and the other large sample size) from a data network library on the web, and read them using code. Write a script using python that reads the network data and plots the data in to a graph (using networkx).
Sample Data: import networkx as nx G=nx.Graph() G.add_node("a") G.add_nodes_from(["b","c"]) G.add_edge(1,2) edge = ("d", "e") G.add_edge(*edge) edge = ("a", "b") G.add_edge(*edge)
# adding a list of edges: G.add_edges_from([("a","c"),("c","d"), ("a",1), (1,"d"), ("a",2)])
nx.draw(G) plt.savefig("simple_path.png") # save as png plt.show() # display
Networked Data:
import csv
from operator import itemgetter
import networkx as nx
from networkx.algorithms import community
# Read in the nodelist file
with open('quakers_nodelist.csv', 'r') as nodecsv:
nodereader = csv.reader(nodecsv)
nodes = [n for n in nodereader][1:]
# Get a list of just the node names (the first item in each
row)
node_names = [n[0] for n in nodes]
# Read in the edgelist file
with open('quakers_edgelist.csv', 'r') as edgecsv:
edgereader = csv.reader(edgecsv)
edges = [tuple(e) for e in edgereader][1:]
# Print the number of nodes and edges in our two lists
print(len(node_names))
print(len(edges))
G = nx.Graph() # Initialize a Graph object
G.add_nodes_from(node_names) # Add nodes to the Graph
G.add_edges_from(edges) # Add edges to the Graph
print(nx.info(G))
#attributes
hist_sig_dict = {}
gender_dict = {}
birth_dict = {}
death_dict = {}
id_dict = {}
nx.set_node_attributes(G, hist_sig_dict,
'historical_significance')
nx.set_node_attributes(G, gender_dict, 'gender')
nx.set_node_attributes(G, birth_dict, 'birth_year')
nx.set_node_attributes(G, death_dict, 'death_year')
nx.set_node_attributes(G, id_dict, 'sdfb_id')
for n in G.nodes(): # Loop through every node, in our data "n" will
be the name of the person
print(n, G.nodes[n]['birth_year'])