决策树(二)在 python 中使用 Matplotlib 注解绘制树形图
转载请注明作者和出处:https://blog.csdn.net/weixin_45814668
微信公众号:qiongjian0427
知乎:https://www.zhihu.com/people/qiongjian0427
Github代码获取:https://github.com/qiongjian/Machine-learning/
Python版本: Python3.x
1. Matplotlib 注解
Matplotlib 提供了一个注解工具 annotations ,可以在数据图形上添加文本注释。注解通常用于解释数据的内容。
1.1 使用文本注解绘制决策树
import matplotlib.pyplot as plt
decisionNode = dict(boxstyle="sawtooth", fc="0.8") # boxstyle为文本框的类型,sawtooth是锯齿形,fc是边框线粗细
leafNode = dict(boxstyle="round4", fc="0.8") # round4表示圆形
arrow_args = dict(arrowstyle="<-") # 箭头样式
def plotNode(nodeTxt, centerPt, parentPt, nodeType):
# 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)
这是第一个版本的 createPlot()函数。
def createPlot():
fig = plt.figure(1, facecolor='white')
fig.clf()
createPlot.axl = plt.subplot(111, frameon=False)
plotNode('JCJD', (0.5, 0.1), (0.1, 0.5), decisionNode)
plotNode('YJD', (0.8, 0.1), (0.3, 0.8), leafNode)
plt<