matplotlib画树
时间: 2023-10-30 20:05:33 浏览: 75
绘制树状图通常使用matplotlib库。具体来说,在matplotlib库中,可以使用annotate()函数来添加文本注解和箭头,以绘制树节点。创建一个绘图函数createPlot(),在该函数中,首先创建一个空白的图形,然后使用plotNode()函数来绘制决策节点和叶子节点的样式。最后使用show()函数显示图形。
以下是一个例子:
```python
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.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('a decision node', (0.5, 0.1), (0.1, 0.5), decisionNode)
plotNode('a leaf node', (0.8, 0.1), (0.3, 0.8), leafNode)
plt.show()
```
以上是使用文本注解和箭头绘制树节点的方法。你可以根据需要调整节点的样式和位置,在plotNode()函数中修改nodeTxt、centerPt、parentPt和nodeType参数来实现你想要的效果。