第三章 决策树 3.2 使用 Matplotlib 注解绘制树形图

上节学习了如何从数据集中创建树,但是字典的表示形式非常不易于理解,而且直接绘制图形也比较困难,这一节我们将使用 Matplotlib库 来创建树形图。


3.2.1 Matplotlib注解

Matplotlib提供了一个注解工具 annotations,可以在数据图形上添加文本注释。

创建一个文件,命名为 treePlotter.py ,然后输入:

# -*- coding:utf-8 -*-
import matplotlib.pyplot as plt


# 定义文本框和箭头格式
decisionNode = dict(boxstyle = "sawtooth", fc = "0.8") # fc 应该是颜色深浅
leafNode = dict(boxstyle = "round4", fc = "0.8")
arrow_args = dict(arrowstyle = "<-")


def plotNode(nodeTxt, centerPt, parentPt, nodeType):
    # centerPt 箭头指向坐标, parentPt 箭头终点坐标
    createPlot.ax1.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.ax1 = plt.subplot(111, frameon = False)
    plotNode(U'决策节点', (0.5, 0.1), (0.1, 0.5), decisionNode) # U 这里指的是 utf 编码
    plotNode(U'叶节点', (0.8, 0.1), (0.3, 0.8), leafNode)
    plt.show()

建立一个运行文件 run_treePlotter.py ,输入:

# run_treePlotter.py
import treePlotter
print '>>> treePlotter.createPlot()'
treePlotter.createPlot()
结果如下:

Python使用matplotlib绘制树形图可以通过以下步骤实现: 首先,需要导入matplotlib库和需要的数据。然后,创建一个新的绘图对象和一个子图对象。接着,使用annotate()函数为每个节点添加注解,并设置节点的坐标和文本。在注解中,可以设置箭头的样式、颜色和文本的格式。最后,需要显示绘图并保存图像。 下面是一个示例代码: ```python import matplotlib.pyplot as plt # 创建树形图数据 data = { &#39;A&#39;: [&#39;B&#39;, &#39;C&#39;], &#39;B&#39;: [&#39;D&#39;, &#39;E&#39;], &#39;C&#39;: [&#39;F&#39;, &#39;G&#39;] } # 创建新的绘图对象和子图对象 fig, ax = plt.subplots() # 添加节点注解 def annotate_tree(node, parent, pos, text_pos): ax.annotate(node, pos, text_pos, arrowprops=dict(arrowstyle=&#39;->&#39;, color=&#39;black&#39;), xycoords=&#39;axes fraction&#39;, textcoords=&#39;axes fraction&#39;, va=&#39;center&#39;, ha=&#39;center&#39;) if node in data: children = data[node] y_off = 1 / (len(children) + 1) for i, child in enumerate(children): annotate_tree(child, node, (pos[0], pos[1] - y_off * (i + 1)), (text_pos[0], text_pos[1] - y_off * (i + 1))) annotate_tree(&#39;A&#39;, None, (0.5, 1), (0.5, 1)) ax.axis(&#39;off&#39;) # 显示绘图 plt.show() ``` 以上代码演示了如何使用matplotlib绘制树形图。通过annotate_tree函数递归地为节点添加注解,并设置箭头的样式和节点的位置。最后,使用ax.axis(&#39;off&#39;)函数将坐标轴关闭,以显示树形图
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值