Get startedGet started for free

Graph differences over time

Now, you'll compute the graph differences over time! To look at the simplest case, here you'll use a window of (month, month + 1), and then keep track of the edges gained or lost over time. This exercise is preparation for the next exercise, in which you will visualize the changes over time.

This exercise is part of the course

Intermediate Network Analysis in Python

View Course

Exercise instructions

  • Inside the for loop:
    • Assign Gs[i] to g1 and Gs[i + window] to g2.
    • Using nx.difference() compute the difference between g2 and g1. Append the result to added.
    • Append the difference between g1 and g2 to removed.
  • Print fractional_changes.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

import networkx as nx  
# Instantiate a list of graphs that show edges added: added
added = []
# Instantiate a list of graphs that show edges removed: removed
removed = []
# Here's the fractional change over time
fractional_changes = []
window = 1

for i in range(len(Gs) - window):
    g1 = Gs[____]
    g2 = Gs[____ + ____]
        
    # Compute graph difference here
    added.append(____)   
    removed.append(____)
    
    # Compute change in graph size over time
    fractional_changes.append((len(g2.edges()) - len(g1.edges())) / len(g1.edges()))
    
# Print the fractional change
print(____)
Edit and Run Code