
2.2 Matplotlib可视化库
在做完数据分析后,有时需要将分析结果展示出来,这便离不开Python可视化工具。Matplotlib是Python中的一个2D绘图工具,是另外一个绘图工具Seaborn的基础包。
2.2.1 初识Matplotlib
Matplotlib最早是为可视化癫痫病人脑皮层电图的相关信号而研发的,因为它在函数的设计上参考了MATLAB,所以叫作Matplotlib。在开源社区的推动下,当前各科学计算领域基于Python的Matplotlib都得到了广泛应用。Matplotlib的原作者John D. Hunter博士是一名神经生物学家,2012年不幸因癌症去世。
由于Matplotlib也是Python的第三方库,因此需要另外安装:

安装完成后,我们来查看Matplotlib版本,代码如下:

通过Matplotlib,开发者仅需要几行代码,便可以生成绘图,如折线图、散点图、柱状图、饼图、直方图、子图等。Matplotlib使用NumPy进行数组运算,并调用一系列其他的Python库来实现硬件交互。
【例2-11】 Matplotlib基本操作。


运行程序,效果如图2-1所示。
提示:Matplotlib还提供了一个名为pylab的模块,其中包括许多NumPy和pyplot模块中的对象,每个Axes(ax)对象都是一个拥有自己坐标系统的绘图区域,Matplotlib对象如图2-2所示。

图2-1 Matplotlib基本操作效果图

图2-2 Matplotlib对象
如图2-2所示,整个图像是Figure(fig)对象。我们的绘图中只有一个坐标系区域,也就是Axes(ax)。每个ax对象都是一个拥有自己坐标系统的绘图区域。如图2-3所示为Matplotlib的绘图结构图。

图2-3 Matplotlib的绘图结构图
表2-5为图像内部各个组件的内容。
表2-5 图像内部各个组件的内容

注意:我们可以把fig想象成Windows的桌面,桌面可以有多个。这样,Axes就是桌面上的图标,Subplot也是图标,它们的区别在于Axes是自由摆放的图标,甚至可以相互重叠,而Subplot是“自动对齐到网格”的图标。但它们本质上都是图标,也就是说,Subplot内部其实也调用Axes,只不过规范了各个Axes的排列罢了。
小技巧:Matplotlib中文显示。
使用Matplotlib时我们会发现,有时图例等设置无法正常显示中文,原因是Matplotlib库中没有中文字体。添加如下代码即可实现中文显示。

2.2.2 Matplotlib经典应用
利用NumPy与Matplotlib,绘制两个高斯分布。
【例2-12】 绘制两个高斯分布。


运行程序,效果如图2-4所示。

图2-4 两个高斯分布
下面尝试绘制饼状图,当前存在3种动物数据,分别为鸭、狗、猪,各自占比为27%、20%和 53%。在数据分析中往往不能只简单地绘制表格,为了更好地观察数据,需要将数据进行可视化展示。
【例2-13】 绘制饼状图。


运行程序,效果如图2-5所示。

图2-5 饼状图显示
除基本的饼状图外,此演示还显示了一些可选功能,如切片标签、自动标记百分比、用“爆炸”来偏移切片、下拉阴影,以及自定义起始角度功能。