Python自定义文本框与连接线绘制方案咨询
自定义决策树样式的实现方案
需求说明
需要创建可完全自定义样式的决策树类图形,要求能绘制带文本的框并通过线条连接所有元素,且不使用限制自定义的模块。此前尝试plt.text()无法实现美观的框间连线。
可行实现(基于Matplotlib的annotate方法)
通过Matplotlib的annotate方法可以实现需求,以下是可用的代码示例:
import matplotlib.pyplot as plt # 文本内容将从列表加载 list_text1 = ['Cat A', 'Item 1', 'Item 2'] text1 = r'$\bf{' + str(list_text1[0]) + '}$' for i in range(len(list_text1)-1): text1 = text1 + '\n' + str(list_text1[i+1]) list_text2 = ['SubCat A.1', 'Item 1', 'Item 2', 'Item 3'] text2 = r'$\bf{' + str(list_text2[0]) + '}$' for i in range(len(list_text2)-1): text2 = text2 + '\n' + str(list_text2[i+1]) list_text3 = ['SubCat A.2', 'Item A', 'Item B', 'Item C'] text3 = r'$\bf{' + str(list_text3[0]) + '}$' for i in range(len(list_text3)-1): text3 = text3 + '\n' + str(list_text3[i+1]) # 文本框位置 area1 = [0.5, 0.8] area2 = [0.2, 0.3] area3 = [0.8, 0.3] # 绘制展示 fig = plt.figure() ax = plt.subplot(111) an1 = ax.annotate(text1, xy=area1, va="bottom", ha="center", bbox=dict(boxstyle="round", fc="w")) an2 = ax.annotate(text2, xy=area1, xytext=area2, va="center", ha="left", bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="-", relpos=(0.5,1))) an3 = ax.annotate(text3, xy=area1, xytext=area3, va="center", ha="left", bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="-", relpos=(0.5,1))) plt.show()
关键自定义点
- 文本框样式:通过
bbox参数可自定义框的形状(如圆角)、填充色等 - 连线样式:通过
arrowprops参数设置连线类型、位置关系 - 文本格式:利用LaTeX语法实现标题加粗,支持多行文本拼接
内容的提问来源于stack exchange,提问作者Hedwin
相关产品推荐
相关产品推荐

