《机器学习实战》学习笔记四:使用Matplotlib注解绘制树形图

本文是《机器学习实战》的学习笔记,主要介绍了如何利用Matplotlib的注解功能绘制树形图。首先,讲解了如何用文本注解绘制树节点,然后通过两个辅助函数确定树的结构。接着,代码示例展示了如何完善树的绘制,包括设置尺寸、位置、x轴和y轴标签,最终得到清晰的树形图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Matplotlib是python的一个绘图库,可以使用其注解功能来绘制图形。
1.使用文本注解绘制树节点

import matplotlib.pyplot as plt
decisionNode = dict(boxstyle="sawtooth",fc="0.8")#定义文本框和箭头格式
leafNode = dict(boxstyle="round4",fc="0.8")
arrow_args = dict(arrowstyle="<-")
def plotNode(nodeTxt,centerPt,parentPt,nodeType):#绘制带箭头的注解
    createPlot.axl.annotate(nodeTxt,xy=parentPt,xycoords='axes fraction',xytext= centerPt,\
    textcoords='axes fraction',va="center",ha="center",bbox=nodeType,arrowprops=arrow_args)
def createPlot():
    fig = plt.figure(1,facecolor='white')
    fig.clf()
    createPlot.axl=plt.subplot(111,frameon=False)
    plotNode('decision',(0.5,0.1),(0.1,0.5),decisionNode)
    plotNode('leaf',(0.8,0.1),(0.3,0.8),leafNode)
    plt.show()

绘制出来的图形如下图所示:
这里写图片描述

2.构造注解树
要绘制一棵树,还需要确定的是熟的叶子节点的个数和树的层数,我们用两个函数来获取以上两个量:

def getNumLeafs(myTree):
    numLeafs = 0
    #firstStr = list(myTree.keys())[0] #python 2.x 写法
    firstSides = list(myTree.keys())  #python 3.x 写法
    firstStr = firstSides[0]  # 找到输入的第一个元素
    secondDict = myTree[firstStr]
    for key in secondDict.keys():
        if type(secondDict[key]).__name__=='dict':
            numLeafs+=getNumLeafs(secondDict[key])
        else:  numLeafs+=1
    return numLeafs

def getTreeDepth(myTree):
    maxDepth = 0
    # firstStr=list(myTree.key())[0]#python3.x 区别
    firstSides = list(myTree.keys())
    firstStr = firstSides[0]  # 找到输入的第一个元素
    secondDict= myTree[firstStr]
    for key in secondDict.keys():
        if type(secondDict[key]).__name__=='dict':
            thisDepth = 1+getTreeDepth(secondDict[key])
        else: thisDepth=1
        if thisDepth>maxDepth:maxDepth = thisDepth
    return maxDepth

由此可以绘制出一棵简单的树:
这里写图片描述

上面绘制树的方法没有规定尺寸和位置,也没有x和y轴标签,我们需要更新以上代码:

def plotTree(myTree,parentPt,nodeText):
    numLeafs = getNumLeafs(myTree)
    depth= getTreeDepth(myTree)
    firstSides=list(myTree.keys())
    firstStr = firstSides[0]
    cntrPt = (plotTree.xOff+(1.0+float(numLeafs))/2.0/plotTree.totalW,plotTree.yOff)
    plotMidText(cntrPt,parentPt,nodeText)
    plotNode(firstStr,cntrPt,parentPt,decisionNode)
    secondDict = myTree[firstStr]
    plotTree.yOff = plotTree.yOff-1.0/plotTree.totalD
    for key in secondDict.keys():
        if type(secondDict[key]).__name__=='dict':
            plotTree(secondDict[key],cntrPt,str(key))
        else:
            plotTree.xOff =plotTree.xOff+1.0/plotTree.totalW
            plotNode(secondDict[key],(plotTree.xOff,plotTree.yOff),cntrPt,leafNode)
            plotMidText((plotTree.xOff,plotTree.yOff),cntrPt,str(key))
    plotTree.yOff = plotTree.yOff+1.0/plotTree.totalD

def createPlot(inTree):
    fig = plt.figure(1,facecolor='white')
    fig.clf()
    axprops = dict(xticks=[],yticks=[])
    createPlot.axl=plt.subplot(111,frameon=False,**axprops)
    plotTree.totalW = float(getNumLeafs(inTree))
    plotTree.totalD = float(getTreeDepth(inTree))
    plotTree.xOff = -0.5/plotTree.totalW;plotTree.yOff=1.0;
    plotTree(inTree,(0.5,1.0),'')
    plt.show()

绘制出的树如图:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值