Get startedGet started for free

Plot number of edge changes over time

You're now going to make some plots! All of the lists that you've created before have been loaded for you in this exercise too. Do not worry about some of the fancy matplotlib code that shows up below: there are comments to help you understand what's going on.

This exercise is part of the course

Intermediate Network Analysis in Python

View Course

Exercise instructions

  • Plot the number of edges added over time. To do this:
    • Use a list comprehension to iterate over added and create a list called edges_added. The output expression of the list comprehension is len(g.edges()), where g is your iterator variable.
    • Pass in the edges_added list to ax1.plot().
  • Plot the number of edges removed over time. Once again, use a list comprehension, this time iterating over removed instead of added.
  • Plot the fractional changes over time by passing it in as an argument to ax2.plot().

Hands-on interactive exercise

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

# Import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)

# Plot the number of edges added over time
edges_added = [____(____) for ____ in ____]
plot1 = ax1.plot(____, label='added', color='orange')

# Plot the number of edges removed over time
edges_removed = [____(____) for ____ in ____]
plot2 = ax1.plot(____, label='removed', color='purple')

# Set yscale to logarithmic scale
ax1.set_yscale('log')  
ax1.legend()

# 2nd axes shares x-axis with 1st axes object
ax2 = ax1.twinx()

# Plot the fractional changes over time
plot3 = ax2.plot(____, label='fractional change', color='green')

# Here, we create a single legend for both plots
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines1 + lines2, labels1 + labels2, loc=0)
plt.axhline(0, color='green', linestyle='--')
plt.show()
Edit and Run Code