Skip to content

Commit a4379bd

Browse files
committed
correct homework
1 parent 6d31611 commit a4379bd

File tree

1 file changed

+35
-5
lines changed

1 file changed

+35
-5
lines changed

D21_Load_dataset/homework.py

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from matplotlib import pyplot as plt
55

66
# 取得鳶尾花資料集
7-
df = sns.load_dataset('iris')
7+
# df = sns.load_dataset('iris')
88
# 箱形圖顯示了數據的總體分布,同時繪製了異常值的數據點。這個物理點讓它們的特定值在樣本之間容易被識別和比較。
99
# sns.boxplot(data = df, orient = "h")
1010
# 當一個或兩個正在研究的變數是分類的時,我們使用像條帶線()、swarmplot()等的圖。
@@ -32,13 +32,43 @@
3232

3333
# FacetGrid 類有助於可視化一個變數的分佈,以及使用多個面板在數據集子集中分別顯示多個變數之間的關係
3434
# 作業:取得另一個 dataset:titanic
35+
# 取得資料集
36+
df = sns.load_dataset('titanic')
3537
df.info()
3638
# 做箱形圖
37-
sns.boxplot(data = df, orient = "h")
39+
sns.barplot(x = "sex", y = "survived", hue = "class", data = df)
40+
plt.show()
41+
# 在上面的示例中,我們可以看到每個class中男性和女性的平均存活率。從情節中,我們可以理解,女性存活人數比男性多。在男性和女性中,更多的存活率來自頭等艙。
42+
3843
# 利用 FacetGrid 繪圖並分析
39-
g = sns.FacetGrid(data = df, col='species',hue = 'species')
40-
g.map(plt.plot, 'X', 'Y1')
44+
# 瞭解性別在各艙等的分布的存活率, 用 survived 跟 sex 拆開
45+
g = sns.FacetGrid(df, col = "survived")
46+
g.map(plt.hist,"sex")
47+
plt.show()
48+
#先檢視各艙位存活人數,此時可以使用groupby函數進行分類,
49+
#其中 survived=1表示存活,survived=0表示死亡,將survived加總即為各艙等生存人數。
50+
51+
df.groupby('pclass').survived.sum()
52+
53+
#加上性別
54+
survived=df.groupby(['pclass','sex']).survived.sum()
55+
survived.plot(kind='bar')
56+
#使用pd.crosstab函數繪製交叉表,交叉表可以很直觀的依據艙位等級及性別來查看存活人數及死亡人數。
57+
#繪製堆疊條形圖,x軸代表依據艙等分成男性及女性,y軸代表人數,其中藍色代表死亡人數,橘色代表存活人數。
58+
survived_counts = pd.crosstab([df.pclass, df.sex],df.survived)
59+
print( survived_counts )
60+
survived_counts.plot(kind='bar', stacked=True)
4161
plt.show()
4262
# 繪製小提琴圖
43-
sns.violinplot(x="day", y="total_bill", hue="smoker", data=df, palette="muted",split=True)
63+
# 直接使用PANDAS dataframe, 當作參數
64+
#條形圖()顯示分類變數和連續變數之間的關係。數據以矩形條表示,其中條的長度表示該類別中數據的比例。
65+
sns.violinplot(data=survived_counts)
66+
plt.show()
67+
# 瞭解性別在各艙等的分布的存活率
68+
g = sns.FacetGrid(df, col = "survived")
69+
g.map(plt.hist,"pclass")
70+
plt.show()
71+
72+
h = sns.FacetGrid(df, col = "survived")
73+
h.map(plt.hist,"sex")
4474
plt.show()

0 commit comments

Comments
 (0)