開始使用免費開始

在同一張圖上疊加多個繪圖

西雅圖市在 Fremont 橋上安裝了計數器,會記錄橋梁東側與西側的單車通行量;這座橋是南北向。

在這個練習中,你會用 for 迴圈與 matplotlib 來探索一天之中橋梁東、西兩側的車流如何變化。了解早晚通勤時段兩側的使用情形,對於未來規劃銜接此高流量路線的單車基礎建設很重要。

當你撰寫需要追蹤目前迭代位置的 for 迴圈時,Python 中很好用的一個函式是 enumerate()

things = ['first thing', 'second', 'yet another']
for ii, item in enumerate(things):
    print(ii, item)
0 first thing
1 second
2 yet another

本練習屬於課程

給 MATLAB 使用者的 Python

檢視課程

練習說明

  • 探索陣列 weekday_traffic 的形狀,分別找出哪個軸對應橋的側別、哪個軸對應一天中的小時。
  • 以欄為單位迭代 weekday_traffic,並使用 enumerate() 來計數迴圈次數。
  • 在每次迴圈中,繪製對應欄位的 weekday_traffic,並使用 sidewalk 中相對應的 label 作為標籤。
  • 建立圖例並顯示圖表。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

sidewalk = ['East','West']

# Explore the shape of the array weekday_traffic
print(weekday_traffic.____)

# Loop over the columns of weekday_traffic, counting the number of iterations
for ii, sidewalk_traffic in ____(weekday_traffic.T):
    # Plot the column with the corresponding label in sidewalk
    plt.plot(sidewalk_traffic, ____=sidewalk[ii])
    
# Create the legend and show the plot
plt.____()
____
編輯並執行程式碼