時間とともに変化するエッジ数をプロットする
それではプロットを作成していきます! これまでに作成したすべてのリストは、この演習でも読み込まれています。以下に出てくる少し凝った matplotlib のコードについては心配しなくて大丈夫です。何をしているかがわかるようにコメントを付けてあります。
この演習はコースの一部です
Python 中級ネットワーク解析
演習の手順
- 時間とともに追加されたエッジ数をプロットします。次のように行います。
- リスト内包表記で
addedを反復し、edges_addedというリストを作成します。リスト内包表記の出力式はlen(g.edges())(ここでgはイテレータ変数)です。 ax1.plot()にedges_addedリストを渡します。
- リスト内包表記で
- 時間とともに削除されたエッジ数をプロットします。ここでもリスト内包表記を使いますが、今回は
addedではなくremovedを反復します。 - 分率的な変化を、
ax2.plot()の引数として渡してプロットします。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# 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()