在《机器学习实战》这本书中,学习到Plotting trees in Python with Matplotlib annotations这个章节,发现里面的一些代码并不是容易理解的,对其中的内容做一个注解,分为两部分,一个是里面代码的语句语法内容,一个是代码的逻辑实现内容,本文则是讲所涉及代码的语法。
decisionNode = dict(boxstyle="sawtooth",fc="0.8")
leafNode = dict(boxstyle="round4",fc="0.8")
arrow_args = dict(arrowstyle="<-")
主要是创建字典,只不过和一般的字典新建方式不一样。boxstyle为文本框的类型,sawtooth是锯齿形,fc是边框线粗细
def plotNode(nodeTxt,centerPt,parentPt,nodeType):
createPlot.ax1.annotate(nodeTxt,xy=parentPt,xycoords='axes fraction',\
xytext=centerPt,textcoords='axes fraction',va="center",ha="center",\
bbox=nodeType,arrowprops=arrow_args)
这部分看上去很长,但弄明白了就很好理解。createPlot是下文中的自定义的函数,ax1是函数的属性,在createPlot中有一句:
createPlot.ax1 = plt.subplot(111,frameon=False,**axprops)
即将函数createPlot的一个自定义属性ax1绑定为matplotlib.pyplot中的subplot,所以annotate便是matplotlib.pyplot中的函数。
这个函数的参数:annotate(s='str' ,xy=(x,y) ,xytext=(l1,l2) ,..)参考
s 为注释文本内容
xy 为被注释的坐标点
xytext 为注释文字的坐标位置
xycoords 参数如下:
- figure points points from the lower left of the figure 点在图左下方
- figure pixels pixels from the lower left of the figure 图左下角的像素
- figure fraction fraction of figure from lower left 左下角数字部分
- axes points points from lower left corner of axes 从左下角点的坐标
- axes pixels pixels from lower left corner of axes 从左下角的像素坐标
- axes fraction fraction of axes from lower left 左下角部分
- data use the coordinate system of the object being annotated(default) 使用的坐标系统被注释的对象(默认)
- polar(theta,r) if not native ‘data’ coordinates t
extcoords 设置注释文字偏移量
arrowprops #箭头参数,参数类型为字典dict
- width the width of the arrow in points 点箭头的宽度
- headwidth the width of the base of the arrow head in points 在点的箭头底座的宽度
- headlength the length of the arrow head in points 点箭头的长度
- shrink fraction of total length to ‘shrink’ from both ends 总长度为分数“缩水”从两端
- facecolor 箭头颜色
bbox给标题增加外框 ,常用参数如下:
- boxstyle方框外形
- facecolor(简写fc)背景颜色
- edgecolor(简写ec)边框线条颜色
- edgewidth边框线条大小
va:verticalalignment设置水平对齐方式 ,可选参数 : 'center' , 'top' , 'bottom' ,'baseline'
ha:horizontalalignment设置垂直对齐方式,可选参数:left,right,center
fig = plt.figure(1,facecolor='white')
facecolor表示图形的底色。
fig.clf()#清空图形
createPlot.ax1 = plt.subplot(111,frameon=False,**axprops)
111表示创建一个1x1的第一个子图,frameon表示是否绘制边框,**axprops表示python中的不定长参数,subplot子图,不定长参数
plotTree.totalW = float(getNumLeafs(inTree))
plotTree.totalD = float(getTreeDepth(inTree))
plotTree.xOff = -0.5/plotTree.totalW;plotTree.yOff = 1.0;
plotTree函数的属性绑定