開始使用免費開始

自動化你的視覺化

Matplotlib 的一大優勢是可以自動因應輸入資料而調整。例如,即使你拿到的資料包含未知數量的類別,仍然可以建立含有每個類別長條的長條圖。

這個練習要你這麼做。你會再次視覺化 2016 年夏季奧運會的得牌選手資料,但這次資料集中包含未知數量的運動項目。這份資料會以 pandas 的 DataFrame 物件載入為 summer_2016_medals,其中有一個名為 "Sport" 的欄位,指出每一列對應到哪個運動項目。還有一個 "Weight" 欄位,記錄每位運動員的體重。

本練習屬於課程

Matplotlib 資料視覺化入門

檢視課程

練習說明

  • sport 作為迴圈變數,走訪 sports 的各個值。
  • 在每次迭代中,篩選出 "Sport" 欄位等於 sport 的列。
  • 在提供的 ax 物件上新增一個長條,標籤為該運動項目名稱,高度為 "Weight" 欄位的平均值,並以其標準差作為 y 軸的誤差棒。
  • 將圖表儲存為檔案 "sports_weights.png"

動手互動練習

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

fig, ax = plt.subplots()

# Loop over the different sports branches
for ____ in ____:
  # Extract the rows only for this sport
  sport_df = ____
  # Add a bar for the "Weight" mean with std y error bar
  ____

ax.set_ylabel("Weight")
ax.set_xticklabels(sports, rotation=90)

# Save the figure to file
____
編輯並執行程式碼