Visualizing connectivity
Here, you're going to visualize how the connectivity of the top connected nodes changes over time. The list of top connected values, top_connected
, from the previous exercise has been loaded.
Remember the defaultdict
you used in Chapter 1? You'll use another defaultdict
in this exercise! As Eric mentioned in the video, a defaultdict
is preferred here as a regular Python dictionary would throw a KeyError
if you try to get an item with a key that is not currently in the dictionary.
This exercise will make use of nested for
loops. That is, you'll use one for
loop inside another.
This exercise is part of the course
Intermediate Network Analysis in Python
Exercise instructions
- Initialize a
defaultdict
of empty lists calledconnectivity
. - Iterate over
top_connected
using afor
loop, and in the body of this outerfor
loop, once again iterate overGs
. Inside this nested loop:- The keys of
connectivity
should be the nodesn
intop_connected
, and the values should be the list of connectivity scores. Therefore, you have to appendlen(list(G.neighbors(n)))
toconnectivity[n]
.
- The keys of
- Iterate over
connectivity
using.items()
and plot the connectivity of each node by passing inconn
toplt.plot()
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Import necessary modules
import matplotlib.pyplot as plt
from collections import defaultdict
# Create a defaultdict in which the keys are nodes and the values are a list of connectivity scores over time
connectivity = ____
for n in ____:
for g in ____:
connectivity[____].____(len(____))
# Plot the connectivity for each node
fig = plt.figure()
for n, conn in ____:
plt.plot(____, label=n)
plt.legend()
plt.show()