在泰坦尼克號資料集中,我需要創建一個圖表,顯示所有班級幸存的乘客百分比。它也應該有三個餅圖。1級存活且未存活,2級存活且未存活,3級。
怎樣才能做到這一點?我已經嘗試過這種型別的代碼,但它產生了錯誤的值。
import pandas as pd
import seaborn as sns # for dataset
df_titanic = sns.load_dataset('titanic')
survived pclass sex age sibsp parch fare embarked class who adult_male deck embark_town alive alone
0 0 3 male 22.0 1 0 7.2500 S Third man True NaN Southampton no False
1 1 1 female 38.0 1 0 71.2833 C First woman False C Cherbourg yes False
2 1 3 female 26.0 0 0 7.9250 S Third woman False NaN Southampton yes True
c1s = len(df_titanic[(df_titanic.pclass==1) & (df_titanic.survived==1)].value_counts())
c2ns = len(df_titanic[(df_titanic.pclass==1) & (df_titanic.survived==0)].value_counts())
此代碼產生真實值,但我需要在 3 個餅圖中
df_titanic.groupby(['pclass' ,'survived']).size().plot(kind='pie', autopct='%.2f')

班級:1,2,3 幸存下來:0,1
uj5u.com熱心網友回復:
- 使用熊貓獲取子圖的正確方法是重塑資料框。
無格式圖
axes = ct.plot(kind='pie', autopct='%.1f%%', subplots=True, figsize=(12, 5), labels=["not survived", "survived"])
uj5u.com熱心網友回復:
代碼:
labels = ["not survived", "survived"] fig, axs = plt.subplots(1,3) axs[0].pie(df_titanic[df_titanic["Pclass"] == 1].groupby(["Survived"]).size(), labels=labels, autopct='%1.1f%%') axs[1].pie(df_titanic[df_titanic["Pclass"] == 2].groupby(["Survived"]).size(), labels=labels, autopct='%1.1f%%') axs[2].pie(df_titanic[df_titanic["Pclass"] == 3].groupby(["Survived"]).size(), labels=labels, autopct='%1.1f%%') plt.show()結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/351752.html
