下面代码为本篇内容的基本代码准备工作:
#!/usr/bin/env python
# coding: utf-8
get_ipython().run_line_magic('matplotlib', 'inline')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
text = pd.read_csv('result.csv')
text.head()
目录
任务二:可视化展示泰坦尼克号数据集中男女中生存与死亡人数的比例图
任务三:可视化展示泰坦尼克号数据集中不同票价的人生存和死亡人数分布情况
任务四:可视化展示泰坦尼克号数据集中不同仓位等级的人生存和死亡人员的分布情况
任务五:可视化展示泰坦尼克号数据集中不同年龄的人生存与死亡人数分布情况
任务六:可视化展示泰坦尼克号数据集中不同仓位等级的人年龄分布情况
任务一:可视化展示泰坦尼克号数据集中男女中生存人数分布情况
用柱状图展示:
sex = text.groupby('Sex')['Survived'].sum()
sex.plot.bar()
plt.title('survived_count')
plt.show()
输出结果:
任务二:可视化展示泰坦尼克号数据集中男女中生存与死亡人数的比例图
首先计算男女中死亡人数,1表示生存,0表示死亡:
text.groupby(['Sex', 'Survived'])['Survived'].count()
# Sex Survived
# female 0 81
# 1 233
# male 0 468
# 1 109
# Name: Survived, dtype: int64
旋转行列:
text.groupby(['Sex', 'Survived'])['Survived'].count().unstack()
# Survived 0 1
# Sex
# female 81 233
# male 468 109
stack()即“堆叠”,作用是将列旋转到行;unstack()即stack()的反操作,将行旋转到列。
用柱状图展示:
text.groupby(['Sex', 'Survived'])['Survived'].count().unstack().plot(kind='bar', stacked='True')
plt.title('survived_count')
plt.ylabel('count')
输出结果:
任务三:可视化展示泰坦尼克号数据集中不同票价的人生存和死亡人数分布情况
计算不同票价中生存与死亡人数 1表示生存,0表示死亡
fare_sur1 = text.groupby(['Fare'])['Survived'].value_counts()
fare_sur1
# Fare Survived
# 0.0000 0 14
# 1 1
# 4.0125 0 1
# 5.0000 0 1
# 6.2375 0 1
# ..
# 247.5208 1 1
# 262.3750 1 2
# 263.0000 0 2
# 1 2
# 512.3292 1 3
# Name: Survived, Length: 330, dtype: int64
绘制折线图,横轴是不同票价,纵轴是存活人数
fig = plt.figure(figsize=(20, 18))
fare_sur1.plot(grid=True)
plt.legend()
plt.show()
输出结果:
对于这种统计性质的且用折线表示的数据,可以考虑将数据排序
fare_sur = text.groupby(['Fare'])['Survived'].value_counts().sort_values(ascending=False)
fare_sur
# Fare Survived
# 8.0500 0 38
# 7.8958 0 37
# 13.0000 0 26
# 7.7500 0 22
# 26.0000 0 16
# ..
# 20.2500 1 1
# 0 1
# 18.7875 1 1
# 0 1
# 15.0500 0 1
# Name: Survived, Length: 330, dtype: int64
排序后绘折线图
fig = plt.figure(figsize=(20, 18))
fare_sur.plot(grid=True)
plt.legend()
plt.show()
输出结果:
任务四:可视化展示泰坦尼克号数据集中不同仓位等级的人生存和死亡人员的分布情况
1表示生存,0表示死亡
pclass_sur = text.groupby(['Pclass'])['Survived'].value_counts()
pclass_sur
# Pclass Survived
# 1 1 136
# 0 80
# 2 0 97
# 1 87
# 3 0 372
# 1 119
# Name: Survived, dtype: int64
import seaborn as sns
sns.countplot(x="Pclass", hue="Survived", data=text)
输出结果:
任务五:可视化展示泰坦尼克号数据集中不同年龄的人生存与死亡人数分布情况
facet = sns.FacetGrid(text, hue="Survived",aspect=3)
facet.map(sns.kdeplot,'Age',shade= True)
facet.set(xlim=(0, text['Age'].max()))
facet.add_legend()
输出结果:
任务六:可视化展示泰坦尼克号数据集中不同仓位等级的人年龄分布情况
text.Age[text.Pclass == 1].plot(kind='kde')
text.Age[text.Pclass == 2].plot(kind='kde')
text.Age[text.Pclass == 3].plot(kind='kde')
plt.xlabel("age")
plt.legend((1,2,3),loc="best")
输出结果: