繪製直方圖

Statistical Thinking in Python (Part 1)

Justin Bois

Teaching Professor at the California Institute of Technology

2008 年美國搖擺州選舉結果

資料取自 Data.gov (https://www.data.gov/)

第 1 章圖 2.003

Statistical Thinking in Python (Part 1)

產生直方圖

import matplotlib.pyplot as plt
_ = plt.hist(df_swing['dem_share'])
_ = plt.xlabel('percent of vote for Obama')
_ = plt.ylabel('number of counties')
plt.show()
Statistical Thinking in Python (Part 1)

座標軸一定要加標籤

Statistical Thinking in Python (Part 1)

2008 年美國搖擺州選舉結果

資料取自 Data.gov (https://www.data.gov/)

第 1 章圖 2.013

Statistical Thinking in Python (Part 1)

不同分箱的直方圖

資料取自 Data.gov (https://www.data.gov/)

第 1 章圖 2.015

Statistical Thinking in Python (Part 1)

設定直方圖的分箱

bin_edges = [0, 10, 20, 30, 40, 50,
                60, 70, 80, 90, 100]
_ = plt.hist(df_swing['dem_share'], bins=bin_edges)
plt.show()

第 1 章圖 2.022

Statistical Thinking in Python (Part 1)

設定直方圖的分箱

_ = plt.hist(df_swing['dem_share'], bins=20)
plt.show()

第 1 章圖 2.027

Statistical Thinking in Python (Part 1)

Seaborn

  • 由 Michael Waskom 編寫的優秀統計資料視覺化套件,建構於 Matplotlib 之上
Statistical Thinking in Python (Part 1)

套用 Seaborn 樣式

import seaborn as sns
sns.set()
_ = plt.hist(df_swing['dem_share'])
_ = plt.xlabel('percent of vote for Obama')
_ = plt.ylabel('number of counties')
plt.show()
Statistical Thinking in Python (Part 1)

Seaborn 風格的直方圖

第 1 章圖 2.038

1 資料取自 Data.gov (https://www.data.gov/)
Statistical Thinking in Python (Part 1)

一起來練習吧!

Statistical Thinking in Python (Part 1)

Preparing Video For Download...