You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除PartialDependenceDisplay绘图中的等高线标签

移除PartialDependenceDisplay中的等高线标签

要移除PartialDependenceDisplay生成的等高线标签,核心是获取绘图中的ContourSet对象,再移除其关联的标签文本。具体实现步骤如下:

  1. 捕获PartialDependenceDisplay实例:from_estimator方法会返回一个PartialDependenceDisplay对象,通过它可以访问绘图的轴和元素。
  2. 定位ContourSet对象:从实例的axes_属性获取所有绘图轴,再从每个轴的collections中筛选出ContourSet类型的对象。
  3. 移除标签文本:通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 02:16:01