matplotlib学习
我们首先对matplotlib库进行学习。
标注设置
要将图像良好,直观的进行表示,需要提前设置一些标注
Figure和Subplot
matplotlib的图像都位于Figure对象中,需要用plt.figure创建一个新的Figure。
创建包含subplot网格的figure是一个非常常见的任务,matplotlib有一个方便的方法plt.subplots,它可以创建一个新的Figure,并返回一个含有已创建的subplot对象的NumPy数组。这是plt.subplots地参数设置:
颜色、标记和线型
matplotlib的plot函数接受一组X和Y坐标,还可以接受一个表示颜色和线型的字符串缩写。
刻度、标签和图例
pyplot接口的设计目的就是交互式使用,含有诸如xlim、xticks和xticklabels之类的方法。它们分别控制图表的范围、刻度位置、刻度标签等。其使用方式有以下两种:
- 调用时不带参数,则返回当前的参数值(例如,plt.xlim()返回当前的X轴绘图范围)。
- 调用时带参数,则设置参数值(例如,plt.xlim([0,10])会将X轴的范围设置为0到10)。
使用matplotlib进行图像绘制和分析
可视化展示泰坦尼克号数据集中生存人数分布情况。
柱状图
使用groupby()进行分组,可视化展示泰坦尼克号数据集中男女性别的生存人数分布情况。
sex = text.groupby('Sex')['Survived'].sum()
sex.plot.bar()
plt.title('survived_count')
plt.show()
可视化结果如图。
观察groupby()后,不使用unstack(),数据的格式。
text.groupby(['Sex','Survived'])['Survived'].count()
获得此时的可视化结果,
text.groupby(['Sex','Survived'])['Survived'].count().plot(kind='bar',stacked='True')
plt.title('survived_count')
plt.ylabel('count')
观察unstack()后的数据格式
text.groupby(['Sex','Survived'])['Survived'].count().unstack()
获得此时的可视化结果。
text.groupby(['Sex','Survived'])['Survived'].count().unstack().plot(kind='bar',stacked='True')
plt.title('survived_count')
plt.ylabel('count')
我们可以发现,在柱状图plot.bar()中,Series和DataFrame的索引将会被用作X(bar)
线性图
同理,我们也可以获得年龄和生存相关的线型图:
df=text.groupby(['Age','Survived'])['Survived'].count().unstack()
df.plot()
可视化展示泰坦尼克号数据集中不同票价的人生存和死亡人数分布情况。
fare_sur = text.groupby(['Fare'])['Survived'].value_counts().sort_values(ascending=False)
fare_sur
可视化如下:
fig = plt.figure(figsize=(20, 18))
fare_sur.plot(grid=True)
plt.legend()
plt.show()
未排序的情况可视化:
seaborn
seaborn利用hue参数,可以简化制作多种分面图:
sns.countplot()函数以bar的形式展示每个类别的数量
import seaborn as sns
sns.set(style="whitegrid")
sns.countplot(x="Pclass", hue="Survived", data=text)
sns.countplot(x="Survived", hue="Pclass", data=text)
分类别的折线图:
facet = sns.FacetGrid(text, hue="Survived",palette='dark',aspect=3)
facet.map(sns.kdeplot,'Age',shade= True )
facet.set(xlim=(0, text['Age'].max()))
facet.add_legend()