matplotlib学习笔记

1.简介

  matplotlib是python的一个2D绘图库,它可以在不同平台上地使用多种通用的绘图格式(hardcopy formats)和交互环境绘制出出版物质量级别的图片。matplotlib可以通过python脚本,python/ipython shell,web application servers以及six图像用户接口工具箱来调用。

  其官方地址:http://matplotlib.org/index.html

2.使用案例

 2.1 绘制决策树*

 *该代码来自于《机器学习实战》

 

 1 # -*- coding: utf-8 -*-
 2 """
 3 Created on Thu Mar 17 20:24:41 2016
 4 
 5 @author: Dale
 6 """
 7 
 8 import matplotlib.pyplot as plt
 9 
10 decisionNode = dict(boxstyle = "sawtooth", fc = "0.8")
11 leafNode = dict(boxstyle = "round4", fc = "0.8")
12 arrow_args = dict(arrowstyle = "<-")
13 
14 def plotNode(nodeTxt, centerPt, parentPt, nodeType):
15     '''
16     下面这个函数原型是class matplotlib.axes.Axes()的成员函数annotate()
17     该函数的作用是为绘制的图上指定的数据点xy添加一个注释nodeTxt,注释的位置由xytext指定
18     其中,xycoords来指定点xy坐标的类型,textcoords指定xytext的类型,xycoords和textcoords的取值如下:
19     ‘figure points’:此时坐标表示坐标原点在图的左下角的数据点
20     ‘figure pixels’:此时坐标表示坐标原点在图的左下角的像素点
21     ‘figure fraction’:此时取值是小数,范围是([0, 1], [0, 1])
22                         ,在图的最左下角时xy是(0,0), 最右上角是(1, 1)
23                         ,其他位置按相对图的宽高的比例取小数值
24     ‘axes points’:此时坐标表示坐标原点在图中坐标的左下角的数据点
25     ‘axes pixels’:此时坐标表示坐标原点在图中坐标的左下角的像素点
26     ‘axes fraction’:类似‘figure fraction’,只不过相对图的位置改成是相对坐标轴的位置
27     ‘data’:此时使用被注释的对象所采用的坐标系(这是默认设置),被注释的对象就是调用annotate这个函数
28             那个实例,这里是ax1,是Axes类,采用ax1所采用的坐标系
29     ‘offset points’:此时坐标表示相对xy的偏移(以点的个数计),不过一般这个是用在textcoords
30     ‘polar’:极坐标类型,在直角坐标系下面也可以用,此时坐标含义为(theta, r)
31     
32     参数arrowprops含义为连接数据点和注释的箭头的类型,该参数是dictionary类型,该参数含有一个
33     名为arrowstyle的键,一旦指定该键就会创建一个class matplotlib.patches.FancyArrowPatch类的实例
34     该键取值可以是一个可用的arrowstyle名字的字符串,也可以是可用的class matplotlib.patches.ArrowStyle类的实例
35     具体arrowstyle名字的字符串可以参考
36     http://matplotlib.org/api/patches_api.html#matplotlib.patches.FancyArrowPatch
37     里面的class matplotlib.patches.FancyArrowPatch类的arrowstyle参数设置
38     
39     函数返回一个类class matplotlib.text.Annotation()的实例
40     '''
41     createPlot.ax1.annotate(nodeTxt, xy = parentPt, xycoords = 'axes fraction', va = 'center', ha = 'center', bbox = nodeType, arrowprops = arrow_args)
42     
43 def createPlot():
44     fig = plt.figure(1, facecolor='white') #创建新的figure 1, 背景颜色为白色
45     fig.clf()  #清空figure 1的内容
46     '''
47      在新建的figure 1里面创建一个1行1列的子figure的网格,并把网格里面第1个子figure的Axes实例axes返回给ax1作为函数createPlot()的属性
48     ,这个属性ax1相当于一个全局变量,可以给plotNode函数使用
49     '''
50     createPlot.ax1 = plt.subplot(111, frameon=False)
51     plotNode('a decision node', (0.5, 0.1), (0.1, 0.5),  decisionNode)
52     plotNode('a leaf node', (0.8, 0.1), (0.3, 0.8), leafNode)
53     plt.show()

 

运行createPlot()函数的结果如下:

 

  

  

posted @ 2016-04-04 23:00  DaleSong  阅读(1696)  评论(0编辑  收藏  举报