Consider the social network shown in the figure below.
In [3]:
# load image
Let's create a graph in networkx to represent that social network.
In [4]:
import networkx as nx
G = nx.Graph() # create a Graph object
people = ["Michael", "Jane", "John", "Peter", "Angie"]
for person in people:
G.add_node(person)
connections = [("Michael", "Jane"), ("Angie", "Michael"),
("John", "Peter"), ("Jane", "John"), ("Angie", "Peter"),
("Angie", "John"), ("Jane", "Angie")]
for person_a, person_b in connections:
G.add_edge(person_a, person_b)
Let's draw the graph.
In [5]:
nx.draw(G, with_labels = True, font_size = 24, node_size = 0)
Imagine a case where we want to load a much bigger graph that that. It would be a lot more convenient to have the graph stored in a file and load it whenever we need it.
We have stored a larger social network in file "social_network_1.txt". Let's load it and see what it looks like.
In [21]:
%%bash
filename="social_network_1.txt"
head -15 $filename
echo Total lines: `cat $filename | wc -l`
In [9]:
g = nx.read_weighted_edgelist("social_network_1.txt")
In [17]:
fig, ax = plt.subplots(figsize = (8, 8))
nx.draw(g, node_color = "black", node_size = 15)
In [32]:
# More complex example: edge attributes, node attributes
Let's use the graph from the previous example and see how we can customize its plot.
In [23]:
g = nx.read_weighted_edgelist("social_network_1.txt") # use other network here
In [25]:
print("Number of nodes: ", len(g))
print("Number of nodes: ", g.number_of_nodes())
In [26]:
print("Number of nodes: ", len(g.nodes()))
In [27]:
print("Nodes: ", g.nodes())
In [28]:
print("Number of edges: ", g.number_of_edges())
In [29]:
print("Number of edges: ", len(g.edges()))
In [31]:
print("Edges: ", g.edges())
How many nodes with attribute X = x?
What is the most common value for attribute X?
...
...
What is the most active node (in terms of people / messages)?
Run these cells before other code cells.
In [16]:
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
In [2]:
%matplotlib inline
In [42]:
nx.read_weighted_edgelist?
In [51]:
g = nx.fast_gnp_random_graph(100, 0.03)
nx.write_edgelist(g, "social_network_1.txt", data = False)
In [ ]: