python数据可视化之 Matplotlib

  可视化是在整个数据挖掘的关键辅助工具,能够清晰的理解数据,从而调整咱们的分析方法。python

  1. Matplotlib 基本概念express

  Matplotlib是python的一个数据可视化工具库,专门用于开发2D图表(包括3D图表), 操做简单。dom

  2. Matplotlib三层结构ide

  容器层函数

  容器层由Canvas、Figure、Axes三部分组成。工具

  Canvas位于最底层的系统层,充当画板,即放置Figure的工具。spa

  Figure是Canvas上方的第一层,也是须要用户来操做的应用层的第一层,在绘图的过程当中充当画布的角色。3d

  Axes是应用层的第二层,在绘图的过程当中至关于画布上的绘图区的角色。对象

  Figure:指整个图形(能够经过plt.figure()设置画布的大小和分辨率等)图片

  Axes(坐标系):数据的绘图区域

  Axis(坐标轴):坐标系中的一条轴,包含大小限制、刻度和刻度标签

  特色为:

  一个figure(画布)能够包含多个axes(坐标系/绘图区),可是一个axes只能属于一个figure。

  一个axes(坐标系/绘图区)能够包含多个axis(坐标轴),包含两个即为2d坐标系,3个即为3d坐标

  辅助显示层

  辅助显示层为Axes(绘图区)内的除了根据数据绘制出的图像之外的内容,主要包括Axes外观(facecolor)、边框线(spines)、坐标轴(axis)、坐标轴名称(axis label)、坐标轴刻度(tick)、坐标轴刻度标签(tick label)、网格线(grid)、图例(legend)、标题(title)等内容。

  图像层

  图像层指Axes内经过plot、scatter、bar、histogram、pie等函数根据数据绘制出的图像

  总结

  Canvas(画板)位于最底层,用户通常接触不到;

  Figure(画布)创建在Canvas之上;

  Axes(绘图区)创建在Figure之上;

  坐标轴(axis)、图例(legend)等辅助显示层以及图像层都是创建在Axes之上。

  3.plt的基本用法

  3.1 Figure对象

  matplotlib的图像都位于Figure对象中,咱们能够调用plt.figure()来建立Figure对象。

  fig = plt.figure()

  figure有一个比较重要的参数figsize,它衡量图片的大小和纵横比(单位为inch):

  fig = plt.figure(figsize=(4,5))

  好比,以上代码表明创建一个宽度为4inch,高度为5inch的figure对象。

  3.2 plot的使用

  有了figure对象以后,就能够利用plot函数做图了。注意不可使用figure对象来调用plot,按照惯例咱们使用plt.plot()来做图,而图像自动分配到上一个创建的figure中。

  3.3 如何在同一个figure内部设置多个图片

  figure对象调用add_subplot函数来添加figure内部不一样位置的图片,add_subplot函数的3个参数分别为figure内部纵向和横向的字图片个数,以及当前建立的子图片是第几个,例如:无锡看妇科的医院 http://www.ytsgfk120.com/

  fig = plt.figure()

  # add_subplot返回的是一个subplot对象

  sp1 = fig.add_subplot(2,3,1)

  sp2 = fig.add_subplot(2,3,2)

  sp3 = fig.add_subplot(2,3,3)

  sp4 = fig.add_subplot(2,3,4)

  fig

  若是要在subplot内部做图,咱们只须要用对应的subplot对象调用plot便可:

  sp1.plot(np.random.randn(50), 'k--', color='r')

  fig

  3.4 如何调整subplot的间距

  有时候各subplot的间距会过大或者太小,这时候与咱们须要使用subplots_adjust函数来调整间距:

  fig.tight_layout() # 调整总体空白

  plt.subplots_adjust(wspace =0, hspace =0) # 调整子图间距

  plt.subplots_adjust(left=None, bottom=None, right=None, top=None,wspace=None,hspace=None)

  参数详解:

  left = 0.125 # the left side of the subplots of the figure

  right = 0.9 # the right side of the subplots of the figure

  bottom = 0.1 # the bottom of the subplots of the figure

  top = 0.9 # the top of the subplots of the figure

  wspace = 0.2 # the amount of width reserved for blank space between subplots,

  # expressed as a fraction of the average axis width

  hspace = 0.2 # the amount of height reserved for white space between subplots,

  # expressed as a fraction of the average axis height

  # 调整fig内部的subplot长宽间距都为0.5

  fig.subplots_adjust(wspace = 0.5, hspace = 0.5)

  fig

相关文章
相关标签/搜索