如何移除PartialDependenceDisplay绘图中的等高线标签
移除PartialDependenceDisplay中的等高线标签
要移除PartialDependenceDisplay生成的等高线标签,核心是获取绘图中的ContourSet对象,再移除其关联的标签文本。具体实现步骤如下:
- 捕获PartialDependenceDisplay实例:
from_estimator方法会返回一个PartialDependenceDisplay对象,通过它可以访问绘图的轴和元素。 - 定位ContourSet对象:从实例的
axes_属性获取所有绘图轴,再从每个轴的collections中筛选出ContourSet类型的对象。 - 移除标签文本:通过
ContourSet的labelTexts属性获取所有标签,逐个移除。
完整代码示例
from sklearn.datasets import make_hastie_10_2 from sklearn.ensemble import GradientBoostingClassifier from sklearn.inspection import PartialDependenceDisplay import matplotlib.pyplot as plt X, y = make_hastie_10_2(random_state=0) clf = GradientBoostingClassifier(n_estimators=100, learning_rate=1.0, max_depth=1, random_state=0).fit(X, y) features = [(0, 1)] # 生成部分依赖图并获取display对象 display = PartialDependenceDisplay.from_estimator(clf, X, features) # 遍历所有轴,移除等高线标签 for ax in display.axes_.ravel(): for contour in ax.collections: if isinstance(contour, plt.ContourSet): for label in contour.labelTexts: label.remove() plt.show()
备选方案(适配不同版本)
如果你的scikit-learn版本中ContourSet的存储方式不同,可以直接遍历当前绘图的所有文本艺术家,筛选出等高线标签并移除:
# 替代上述移除标签的代码块 for artist in plt.gca().artists: # 通过文本格式判断是否为等高线数值标签 if isinstance(artist, plt.Text) and artist.get_text().replace('.', '', 1).isdigit(): artist.remove()
内容的提问来源于stack exchange,提问作者Aart
相关产品推荐
相关产品推荐

