開始使用免費開始

在分布中凸顯特定數值

有時你需要先整理資料,才能做出更好的視覺化。處理遺漏值常用的方法有 .dropna().fillna()。你也可以用篩選方式移除離群值,例如對特定欄位使用 .quantile() 設定分位數門檻,過濾高於或低於某個百分位數的資料列。

你也在影片裡看到,如何在圖上以一條垂直線強調特定的 x 位置:

Axes.axvline(x=0, color=None, ...)

在這個練習中,你會最後再看一次全球所得分布,接著移除高於第 95 百分位的離群值,繪製分布,並同時標示平均數與中位數。已經為你匯入 pandaspdseabornsnsmatplotlib.pyplotplt,而且先前練習用到的 income DataFrame 也已在你的工作空間中可用。

本練習屬於課程

在 Python 中匯入與管理財務資料

檢視課程

練習說明

  • 將欄位 'Income per Capita' 指派給 inc_per_capita
  • 過濾只保留 inc_per_capita 中低於第 95 百分位的列,並重新指派回同一變數。
  • 為過濾後的 inc_per_capita 繪製預設的長條圖(histogram),並指派給 ax
  • 使用 ax.axvline() 並設 color='b',以藍色凸顯 inc_per_capita 的平均數。
  • 使用 ax.axvline() 並設 color='g',以綠色凸顯其中位數。顯示結果!

動手互動練習

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

# Create inc_per_capita
inc_per_capita = ____

# Filter out incomes above the 95th percentile
inc_per_capita = inc_per_capita[____ < ____]

# Plot histogram and assign to ax
ax = ____

# Highlight mean
ax.axvline(inc_per_capita.mean(), color='b')

# Highlight median
ax.axvline(inc_per_capita.median(), color='g')

# Show the plot
plt.show()
編輯並執行程式碼