可视化 hscredit.core.viz

46+ 种风控可视化图表:分箱趋势、KS / ROC / PR / Lift / Gain、评分分布、策略阈值、 Vintage、变量稳定性、客群漂移、决策树图等。

推荐入口

新代码优先使用以下四个公开方法;其他同类入口主要用于兼容既有代码或特定报告布局。

方法

推荐场景

bin_plot

原始特征或分箱统计表的样本结构、坏率和分箱指标

ks_plot

KS / ROC 评估;用 pos_label 明确正类,用 score_direction 明确评分方向

lift_plot

按预测坏概率排序的 Lift 分箱效果

plot_model_feature_importance

模型原生重要性、SHAP 分布和单特征依赖关系

样式与调用契约

import hscredit 会自动调用 hscredit.init_setting(),统一配置内置中文字体、 Matplotlib 基础样式和负号显示。set_style / reset_style 仅用于在该基线上 临时覆盖主题,不是独立的初始化入口。

推荐方法独立创建画布时返回 Matplotlib Figurebin_plotlift_plot 通过 ax 嵌入已有画布;ks_plot(curve='ks'/'roc') 通过 ax 嵌入单图, 默认双图模式则传入 axes=[ks_ax, roc_ax]。嵌入时 bin_plot / ks_plot 返回所用 Axeslift_plot 返回该轴所属 Figurebin_plot(..., ax=ax, return_frame=True) 返回 (ax, 分箱统计表)save 路径的文件格式由后缀推断,例如 .png.svg.pdf

可视化模块 (viz).

推荐的公开绘图入口: - 特征分箱图 (bin_plot) - KS/ROC 曲线图 (ks_plot) - 特征分布图 (hist_plot) - 特征相关性热力图 (corr_plot) - PSI稳定性分析图 (psi_plot) - Lift 提升图 (lift_plot) - DataFrame表格图 (dataframe_plot) - 时间分布图 (distribution_plot) - 模型特征重要性图 (plot_model_feature_importance) - 逻辑回归系数误差图 (plot_weights)

score_*feature_importance_plot 等同类函数为兼容或特定报告场景入口; 新代码优先使用以上推荐方法。全局图片样式由 hscredit.init_setting() 初始化,set_style / reset_style 仅作为可选主题覆盖层。

金融风控专用图表 (risk_plots): - ROC曲线图 (roc_plot) - PR曲线图 (pr_plot) - Lift提升图 (lift_plot) - Gain增益图 (gain_plot) - 混淆矩阵图 (confusion_matrix_plot) - 校准曲线图 (calibration_plot) - 评分分布对比图 (score_dist_plot) - 评分分箱效果图 (score_bin_plot) - 决策阈值分析图 (threshold_analysis_plot) - 策略效果对比图 (strategy_compare_plot) - Vintage账龄曲线图 (vintage_plot) - 特征重要性图 (feature_importance_plot) - 审批通过率趋势图 (approval_rate_trend_plot) - 坏样本率趋势图 (bad_rate_trend_plot)

辅助函数已移至 utils 模块: - init_setting -> hscredit.utils.init_setting - feature_describe -> hscredit.utils.feature_describe - round_float -> hscredit.utils.round_float - feature_bins -> hscredit.utils.feature_bins

参考 scorecardpipeline 实现优化而来。

hscredit.core.viz.bin_plot(data, target=None, feature=None, desc='', figsize=(12, 7), colors=None, save=None, anchor=None, max_len=35, fontdict=None, hatch=True, ending='分箱图', title=None, n_bins=10, method='quantile', rules=None, show_data_points=True, show_overall_bad_rate=True, show_metric_summary=True, metric_summary_layout='compact', show_rate_axis=True, iv=True, return_frame=False, ax=None, orientation='horizontal', **kwargs)[源代码]

特征分箱可视化图.

支持两种使用方式:

方式1:传入原始数据(toad 模式)

# DataFrame + 列名
bin_plot(df, x='feature_name', target='target')

# Series + 目标数组
bin_plot(df['feature'], target=df['target'])

# 使用已创建的画布
fig, axes = plt.subplots(2, 3, figsize=(18, 10))
for i, col in enumerate(features):
    bin_plot(df[col], target=y, ax=axes[i], title=f'{col}分箱')

方式2:传入分箱统计表(scorecardpipeline 模式)

# 传入已计算好的分箱统计表
bin_plot(feature_table, desc="特征描述")
参数:
  • data (DataFrame | Series) -- 数据(DataFrame、Series 或分箱统计表)

  • target (str | Series | ndarray | None) -- 目标变量(列名、Series 或数组)

  • feature (str | None) -- 特征列名(当 data 为 DataFrame 且不明确时使用)

  • desc (str) -- 特征中文描述

  • figsize (tuple) -- 图像尺寸(创建新图时使用)

  • colors (List[str] | None) -- 配色方案

  • save (str | None) -- 保存路径

  • anchor (float | None) -- 图例位置;默认根据实际图高自适应,显式传入时以用户值为准

  • max_len (int) -- 分箱标签最大长度

  • fontdict (dict | None) -- 字体样式

  • hatch (bool) -- 是否显示斜线

  • ending (str) -- 标题后缀

  • title (str | None) -- 完整标题(优先级高于 desc + ending)

  • n_bins (int) -- 分箱数量(仅用于方式1)

  • method (str) -- 分箱方法(仅用于方式1),可选 'quantile' 或 'uniform'

  • rules (List | None) -- 自定义分箱边界(仅用于方式1)

  • show_data_points (bool) -- 是否显示数据点标记

  • show_overall_bad_rate (bool) -- 是否显示整体坏样本率参考线

  • show_metric_summary (bool) -- 是否显示左上角的指标角标(IV/KS/LIFT/趋势摘要),默认显示

  • metric_summary_layout (str) -- 指标摘要布局;'compact' 为紧凑左对齐, 'full_width_center' 为与坐标轴等宽的单行居中摘要条

  • show_rate_axis (bool) -- 是否显示坏样本率坐标轴刻度与标签(趋势线本身始终保留),默认显示

  • iv (bool) -- 是否显示 IV 值(暂不支持)

  • return_frame (bool) -- 是否返回分箱统计表

  • ax (Any | None) -- 可选的 matplotlib Axes 对象,用于在已有画布上绘图

  • orientation (str) -- 图表方向,'horizontal'/'h'(横向,默认) 或 'vertical'/'v'(纵向)

  • kwargs -- 其他参数(兼容性)

返回:

独立绘图时返回 Figure 或 (Figure, DataFrame);传入 ax 时返回 Axes,return_frame=True 时返回 (Axes, DataFrame)

参考样例

>>> from hscredit.core.viz import bin_plot
>>> # 方式1:原始数据(自动分箱)
>>> bin_plot(df, feature='score', target='target', n_bins=10, method='quantile')
>>> # Series + 目标数组
>>> bin_plot(df['score'], target=df['target'])
>>> # 方式2:传入已算好的分箱统计表
>>> from hscredit.report import feature_bin_stats
>>> table = feature_bin_stats(df, 'score', target='target')
>>> bin_plot(table, desc='衡枢鉴真分')
>>> # 纵向 + 返回统计表
>>> fig, stat = bin_plot(df, feature='score', target='target',
...                      orientation='vertical', return_frame=True)
hscredit.core.viz.bin_2d_plot(data, features=None, target=None, *, binner=None, method='quantile', max_n_bins=5, min_bin_size=0.02, figsize=None, colors=None, title=None, annot=True, fontsize=10, save=None, binner_kwargs=None)[源代码]

两个变量交叉分箱联合分析图(3×3 布局).

布局(特征1 为行维度,特征2 为列维度):

KS 曲线

特征2分箱图

风险拒绝比

样本占比

坏样本率

特征1分箱图

LIFT

坏账改善

KS 曲线

  • 两个单变量分箱图(复用 bin_plot(),与交叉热力图共用坐标系):特征2分箱图 (纵向,bin 落在 x 轴)置于第1行中列,与同列热力图(坏样本率/坏账改善)按列对齐; 特征1分箱图(横向,bin 落在 y 轴)置于第2行右列,与同行热力图(样本占比/坏样本率) 按行对齐

  • 两个 KS 曲线复用 ks_plot()curve='ks',仅 KS 曲线,去掉 ROC),分置左上、右下角

  • 其余 5 格为两变量分箱交叉指标热力图(类似相关性图,均以百分数标注): 样本占比、坏样本率、LIFT、风险拒绝比、坏账改善

支持两种输入方式:

方式1:原始数据

>>> bin_2d_plot(df, features=['特征1', '特征2'], target='target')

方式2:已拟合的 OptimalBinning2D

>>> from hscredit.core.binning import OptimalBinning2D
>>> b = OptimalBinning2D(max_n_bins=5).fit(df, y=df['target'], features=['f1', 'f2'])
>>> bin_2d_plot(b)
参数:
  • data -- DataFrame(方式1)或已拟合的 OptimalBinning2D(方式2)

  • features (List[str] | None) -- [特征1, 特征2],特征1 为行维度,特征2 为列维度(方式1 需要)

  • target (str | Series | ndarray | None) -- 目标列名或数组(方式1 需要)

  • binner -- 已拟合的 OptimalBinning2D(可选,优先级高于由 data 构造)

  • method (str) -- 分箱方法(方式1 构造 OptimalBinning2D 时使用)

  • max_n_bins (int) -- 最大分箱数(方式1)

  • min_bin_size (float | int) -- 每箱最小样本占比(方式1)

  • figsize (tuple | None) -- 图像尺寸,None 时根据分箱数自动计算

  • colors (List[str] | None) -- 配色方案

  • title (str | None) -- 图表总标题

  • annot (bool) -- 热力图是否标注数值

  • fontsize (int) -- 单元格字体大小

  • save (str | None) -- 保存路径

  • binner_kwargs (Dict | None) -- 透传给 OptimalBinning2D 的其他参数(方式1)

返回:

matplotlib Figure

参考样例

>>> from hscredit.core.viz import bin_2d_plot
>>> # 方式1:原始数据,内部自动二维分箱
>>> bin_2d_plot(df, features=['score', '多头数'], target='target', max_n_bins=5)
>>> # 方式2:已拟合的 OptimalBinning2D
>>> from hscredit.core.binning import OptimalBinning2D
>>> b = OptimalBinning2D(max_n_bins=5).fit(df, y=df['target'], features=['f1', 'f2'])
>>> bin_2d_plot(b)
hscredit.core.viz.corr_plot(data, figure_size=None, fontsize=16, mask=False, save=None, annot=True, max_len=35, linewidths=0.1, fmt='.2f', step=11, linecolor='white', ax=None, figsize=(16, 8), **kwargs)[源代码]

特征相关性热力图.

参数:
  • data -- 特征数据

  • figure_size -- 图像尺寸(创建新图时使用)

  • fontsize -- 字体大小

  • mask -- 是否只显示下三角

  • save -- 保存路径

  • annot -- 是否显示数值

  • max_len -- 特征名最大长度

  • fmt -- 数值格式

  • step -- 色阶步数

  • linewidths -- 边框宽度

  • linecolor -- 边框颜色

  • ax -- 可选的 matplotlib Axes 对象

返回:

matplotlib Figure 或 Axes(传入 ax 时返回 ax)

参考样例

>>> from hscredit.core.viz import corr_plot
>>> corr_plot(df[['score', 'age', 'income']])
>>> corr_plot(df[num_cols], mask=True, annot=False)   # 只显示下三角、不标注数值
hscredit.core.viz.ks_plot(score, target, title='', fontsize=14, figsize=(16, 8), save=None, colors=None, anchor=None, axes=None, ax=None, curve='both', pos_label=1, score_direction='auto')[源代码]

KS曲线和ROC曲线.

参数:
  • score -- 预测分数或评分

  • target -- 真实标签

  • title -- 图表标题

  • fontsize -- 字体大小

  • figsize -- 图像尺寸(创建新图时使用)

  • save -- 保存路径

  • colors -- 配色方案

  • anchor -- 图例位置;默认根据实际图高自适应,显式传入时以用户值为准

  • axes -- 可选的 matplotlib Axes 对象数组 [ax1, ax2]

  • ax -- 可选的单个 Axes(配合 curve='ks'/'roc' 仅绘制单条曲线时使用)

  • curve --

    绘制内容,默认 'both'

    • 'both':同时绘制 KS 曲线与 ROC 曲线(需两个 Axes)

    • 'ks':仅绘制 KS 曲线(单个 Axes,便于嵌入组合图)

    • 'roc':仅绘制 ROC 曲线(单个 Axes)

  • pos_label -- 正样本标签,默认 1;字符串或非 0/1 标签必须显式指定

  • score_direction -- 分数方向,可选 auto(默认,AUC 小于 0.5 时自动反向)、 higher_risk(值越大正样本风险越高)或 higher_safe(值越大越安全)

返回:

matplotlib Figure 或 Axes(嵌入模式下返回所用 Axes)

参考样例

>>> from hscredit.core.viz import ks_plot
>>> ks_plot(df['score'], df['target'], title='衡枢鉴真分')
>>> ks_plot(y_prob, y_true, curve='ks')   # 仅 KS 曲线
hscredit.core.viz.hist_plot(score, y_true=None, figsize=(15, 10), bins=30, save=None, labels=None, desc='', anchor=None, fontsize=14, kde=False, title=None, ax=None, **kwargs)[源代码]

特征值分布直方图.

参数:
  • score -- 特征值

  • y_true -- 标签

  • figsize -- 图像尺寸(创建新图时使用)

  • bins -- 分箱数

  • save -- 保存路径

  • labels -- 图例标签

  • desc -- 描述

  • anchor -- 图例位置;默认根据实际图高自适应,显式传入时以用户值为准

  • fontsize -- 字体大小

  • kde -- 是否显示核密度估计

  • title -- 完整标题(优先级高于 desc)

  • ax -- 可选的 matplotlib Axes 对象

  • kwargs -- 其他参数

返回:

matplotlib Figure 或 Axes(传入 ax 时返回 ax)

参考样例

>>> from hscredit.core.viz import hist_plot
>>> hist_plot(df['score'])                              # 整体分布
>>> hist_plot(df['score'], y_true=df['target'], kde=True)  # 好/坏分组叠加 + 核密度
hscredit.core.viz.psi_plot(expected, actual, y=None, labels=None, desc='', save=None, colors=None, figsize=(15, 8), anchor=None, width=0.35, result=False, plot=True, max_len=None, hatch=True, title=None, **kwargs)[源代码]

PSI稳定性分析图.

支持两种输入方式: 1. 直接传入原始分数数据(pd.Series 或单列 pd.DataFrame),自动分箱计算PSI 2. 传入已计算好的分箱表(pd.DataFrame,含 '分箱' 列),直接绘图

参数:
  • expected -- 期望分布(原始数据或分箱表)

  • actual -- 实际分布(原始数据或分箱表)

  • y -- 目标变量(pd.Series),用于绘制坏样本率折线图。当传入原始数据时, 应与 expected/actual 长度之和一致,按相同分箱计算坏样本率;为 None 时仅展示 预期/实际样本占比,不创建坏样本率副轴和图例。

  • labels -- 标签

  • desc -- 描述

  • save -- 保存路径

  • colors -- 配色

  • figsize -- 图像尺寸

  • anchor -- 图例位置;默认根据实际图高自适应,显式传入时以用户值为准

  • width -- 柱宽

  • result -- 是否返回统计表

  • plot -- 是否绘图

  • max_len -- 标签最大长度

  • hatch -- 是否显示斜线

  • title -- 完整标题(优先级高于 desc)

返回:

result=True 时返回 PSI 分箱统计表(pd.DataFrame),否则返回图对象

参考样例

>>> from hscredit.core.viz import psi_plot
>>> # 原始分数:自动分箱并计算 PSI
>>> psi_plot(train_df['score'], test_df['score'], desc='评分')
>>> # 叠加坏样本率折线,并返回统计表
>>> combined_y = pd.concat([train_df['target'], test_df['target']], ignore_index=True)
>>> tbl = psi_plot(train_df['score'], test_df['score'], y=combined_y, result=True)
hscredit.core.viz.dataframe_plot(df, row_height=0.4, font_size=14, header_color=None, row_colors=None, edge_color='w', bbox=[0, 0, 1, 1], header_columns=0, ax=None, save=None, **kwargs)[源代码]

将DataFrame转换为图像.

参数:
  • df -- 数据框

  • row_height -- 行高

  • font_size -- 字体大小

  • header_color -- 表头颜色

  • row_colors -- 行颜色

  • edge_color -- 边框颜色

  • bbox -- 边框

  • header_columns -- 表头列数

  • ax -- 坐标系

  • save -- 保存路径

返回:

matplotlib Figure

参考样例

>>> from hscredit.core.viz import dataframe_plot
>>> # 将统计表渲染为图片,便于嵌入报告或拼接子图
>>> dataframe_plot(summary_df, save='摘要表.png')
hscredit.core.viz.distribution_plot(data, date='date', target='target', save=None, figsize=(10, 6), colors=None, freq='M', anchor=None, result=False, hatch=True, overdue=None, dpds=None, title=None)[源代码]

样本时间分布图.

支持两种模式: 1. 单目标模式:传入 target 列名,展示好/坏样本堆叠柱状图 + 坏样本率折线 2. 多逾期口径模式:传入 overdue + dpds,展示样本总数柱状图 + 多条坏样本率折线

参数:
  • data -- 数据集

  • date -- 日期列名

  • target -- 目标列名(单目标模式使用)

  • save -- 保存路径

  • figsize -- 图像尺寸

  • colors -- 配色

  • freq -- 日期频率,'D'/'W'/'M'/'Q'

  • anchor -- 图例位置;默认根据实际图高自适应,显式传入时以用户值为准

  • result -- 是否返回统计表

  • hatch -- 是否显示斜线

  • overdue -- 逾期列名列表,如 ['dpd7', 'dpd15', 'dpd30'](多逾期口径模式)

  • dpds -- 逾期阈值列表,与 overdue 一一对应,如 [1, 1, 1]

  • title -- 图表标题

返回:

matplotlib Figure or pd.DataFrame

参考样例

>>> # 单目标模式
>>> distribution_plot(df, date='apply_date', target='target')
>>> # 多逾期口径模式
>>> distribution_plot(
...     df, date='apply_date',
...     overdue=['dpd7', 'dpd15', 'dpd30'], dpds=[1, 1, 1]
... )
hscredit.core.viz.bin_trend_plot(data, feature, target, dimension_cols=None, date_col=None, date_freq='M', method='quantile', max_n_bins=10, min_bin_size=0.02, rules=None, special_codes=None, shared_bins='max_samples', sort_by=None, sort_order='asc', max_groups=None, figsize=None, colors=None, title=None, show_overall=True, show_stats=True, orientation='vertical', dpi=150, save=None, anchor=None, **kwargs)[源代码]

绘制特征分箱风险趋势图.

该图表集成了特征在不同维度下的样本分布、坏率走势、统计指标等信息。 支持按时间维度(自动聚合)或指定维度列进行分组展示。

参数:
  • data (DataFrame) -- 输入数据

  • feature (str) -- 特征列名

  • target (str) -- 目标变量列名(0/1)

  • dimension_cols (str | List[str] | None) -- 维度列名(单维或多维),用于分组展示

  • date_col (str | None) -- 日期列名,如提供则按日期分组

  • date_freq (str) -- 日期聚合频率,'D'/'W'/'M'/'Q',默认'M'

  • method (str) -- 分箱方法,取值与 OptimalBinning.VALID_METHODS 一致(共17种), 如 'quantile'/'uniform'/'cart' 等,默认 'quantile'

  • max_n_bins (int) -- 最大分箱数,默认10

  • min_bin_size (float) -- 最小箱占比,默认0.02

  • rules (Dict | None) -- 预定义分箱规则 {特征名: 分箱边界列表}

  • special_codes (List | None) -- 特殊值列表

  • shared_bins (str | bool | None) -- 各分组是否共享同一切分点,默认 'max_samples' - 'first': 使用第一个分组(最早时间/第一个维度值)的切分点 - 'last': 使用最后一个分组(最近时间/最后一个维度值)的切分点 - 'max_samples': 使用样本量最多的分组的切分点(默认) - False 或 None: 每个分组独立计算切分点

  • sort_by (str | None) -- 排序列名,None表示不排序,默认按维度值排序

  • sort_order (str) -- 排序方向,'asc'/'desc'

  • max_groups (int | None) -- 最大展示分组数,None表示全部展示

  • figsize (tuple | None) -- 图像尺寸,None时自动计算;多列面板会按实际轴装饰自适应到最小安全间距

  • colors (List[str] | None) -- 配色方案

  • title (str | None) -- 图表标题

  • show_overall (bool) -- 是否显示整体样本面板

  • show_stats (bool) -- 是否显示统计指标

  • orientation (str) -- 图表方向,'vertical'(纵向,默认)或 'horizontal'

  • dpi (int) -- 图像分辨率

  • save (str | None) -- 保存路径

  • anchor (float | None) -- 图例位置;默认根据实际图高自适应,显式传入时以用户值为准

  • kwargs -- 其他参数

返回:

matplotlib Figure

返回类型:

Figure

参考样例

>>> # 按月份查看特征趋势
>>> fig = bin_trend_plot(
...     df, feature='age', target='bad', date_col='apply_date'
... )
>>> # 按客群维度查看
>>> fig = bin_trend_plot(
...     df, feature='score', target='bad', dimension_cols='customer_type'
... )
>>> # 多维度交叉
>>> fig = bin_trend_plot(
...     df, feature='income', target='bad',
...     dimension_cols=['region', 'channel']
... )
>>> # 自定义分箱规则
>>> fig = bin_trend_plot(
...     df, feature='score', target='bad',
...     rules={'score': [300, 500, 600, 700, 800]}
... )
>>> # 各分组使用第一个分组的切分点
>>> fig = bin_trend_plot(
...     df, feature='score', target='bad', date_col='apply_date',
...     shared_bins='first'
... )
hscredit.core.viz.batch_bin_trend_plot(data, features, target, dimension_cols=None, date_col=None, date_freq='M', sort_by='iv', max_features=10, figsize_per_feature=None, save_dir=None, **kwargs)[源代码]

批量绘制多个特征的风险趋势图.

参数:
  • data (DataFrame) -- 输入数据

  • features (List[str]) -- 特征列表

  • target (str) -- 目标变量列名

  • dimension_cols (str | List[str] | None) -- 维度列名

  • date_col (str | None) -- 日期列名

  • date_freq (str) -- 日期聚合频率,'D' 日 / 'W' 周 / 'M' 月 / 'Q' 季度,默认 'M'

  • sort_by (str) -- 特征排序指标,'iv'``(默认)/ ``'ks' / 'auc',决定绘图先后顺序

  • max_features (int) -- 最大绘制特征数,默认 10

  • figsize_per_feature (tuple | None) -- 每个特征的图尺寸,默认 None(由 bin_trend_plot 按面板数量和方向自动计算, 并按实际轴装饰自适应相邻列间距)

  • save_dir (str | None) -- 保存目录,提供时各特征图按特征名保存为图片

  • kwargs -- 其他参数传递给 bin_trend_plot

返回:

特征名到 Figure 的字典

返回类型:

Dict[str, Figure]

参考样例

>>> from hscredit.core.viz import batch_bin_trend_plot
>>> figs = batch_bin_trend_plot(
...     df, features=['score', 'age', 'income'], target='target',
...     date_col='放款时间', date_freq='M', sort_by='iv', max_features=5,
... )
>>> figs['score']   # 取单个特征的图
hscredit.core.viz.bin_overdues_plot(data, feature=None, overdue=None, dpds=None, bin_table=None, method='quantile', max_n_bins=10, min_bin_size=0.02, rules=None, shared_bins='max_samples', figsize=None, colors=None, title=None, show_stats=True, max_cols=3, save=None, **kwargs)[源代码]

绘制多个逾期天数的分箱图(横向展示).

支持两种输入方式: 1. 原始数据 + overdue + dpds:根据原始数据计算分箱并绘图 2. 分箱表(来自 feature_bin_stats):直接解析多级表头分箱表并绘图

参数:
  • data (DataFrame) -- 输入数据(原始数据模式)或分箱表(当传入 bin_table 时忽略)

  • feature (str | None) -- 特征列名(原始数据模式需要)

  • overdue (List[str] | None) -- 逾期天数列名列表,如 ['dpd7', 'dpd15', 'dpd30']

  • dpds (List[int] | None) -- 逾期阈值列表,与 overdue 一一对应,如 [1, 1, 1] 表示逾期天数>=该阈值时视为坏样本

  • bin_table (DataFrame | None) -- 分箱表(来自 feature_bin_stats 的多级表头 DataFrame) 传入后将直接使用分箱表绘图,忽略 data/overdue/dpds 参数

  • method (str) -- 分箱方法,默认 'quantile'

  • max_n_bins (int) -- 最大分箱数,默认10

  • min_bin_size (float) -- 最小箱占比,默认0.02

  • rules (Dict | None) -- 预定义分箱规则 {特征名: 分箱边界列表}

  • shared_bins (str | bool | None) -- 各逾期目标是否共享同一切分点,默认 'max_samples' - 'first': 使用第一个逾期定义的切分点 - 'last': 使用最后一个逾期定义的切分点 - 'max_samples': 使用有效样本量最多的逾期定义的切分点(默认) - False 或 None: 每个逾期定义独立计算切分点

  • figsize (tuple | None) -- 图像尺寸,None时自动计算

  • colors (List[str] | None) -- 配色方案

  • title (str | None) -- 图表总标题

  • show_stats (bool) -- 是否显示统计指标

  • max_cols (int) -- 每行最多显示几个子图

  • save (str | None) -- 保存路径

  • kwargs -- 其他参数

返回:

matplotlib Figure

返回类型:

Figure

参考样例

>>> # 方式1:使用原始数据
>>> fig = bin_overdues_plot(
...     df,
...     feature='score',
...     overdue=['dpd7', 'dpd15', 'dpd30'],
...     dpds=[1, 1, 1],
...     max_n_bins=5
... )
>>> # 方式2:使用 feature_bin_stats 生成的分箱表
>>> from hscredit.report.feature_analyzer import feature_bin_stats
>>> bin_table = feature_bin_stats(
...     df,
...     feature='score',
...     overdue=['MOB1', 'MOB3'],
...     dpds=[0, 7]
... )
>>> fig = bin_overdues_plot(bin_table=bin_table)
hscredit.core.viz.plot_weights(summary, save=None, figsize=(15, 8), fontsize=14, colors=None, ax=None)[源代码]

逻辑回归模型系数误差图.

展示逻辑回归模型各特征的系数估计值及其95%置信区间, 用于评估特征的显著性及系数的稳定性。

参数

参数:
  • summary -- 逻辑回归模型的统计摘要,可以是以下两种形式之一: - pd.DataFrame: LogisticRegression.summary() 的返回结果 - LogisticRegression: hscredit 的 LogisticRegression 模型对象

  • save -- 图片保存路径,如果传入路径中有文件夹不存在,会自动创建,默认 None

  • figsize -- 图片大小(创建新图时使用),默认 (15, 8)

  • fontsize -- 字体大小,默认 14

  • colors -- 图片主题颜色列表,长度为3,默认为 ["#2639E9", "#F76E6C", "#FE7715"]

  • ax -- 可选的 matplotlib Axes 对象,用于在已有画布上绘图

返回

返回:

matplotlib Figure 或 Axes 对象

参考样例

使用 DataFrame 作为输入:

>>> from hscredit.core.models import LogisticRegression
>>> from hscredit.core.viz import plot_weights
>>>
>>> # 训练模型
>>> model = LogisticRegression(calculate_stats=True)
>>> model.fit(X_train, y_train)
>>>
>>> # 方式1:传入 summary DataFrame
>>> summary = model.summary()
>>> fig = plot_weights(summary)
>>>
>>> # 方式2:直接传入模型对象
>>> fig = plot_weights(model)

在已有画布上绘图:

>>> fig, axes = plt.subplots(1, 2, figsize=(16, 6))
>>> plot_weights(model1, ax=axes[0])
>>> plot_weights(model2, ax=axes[1])

保存图片:

>>> fig = plot_weights(model, save='./output/weight_plot.png')

自定义样式:

>>> fig = plot_weights(
...     model,
...     figsize=(12, 6),
...     fontsize=12,
...     colors=['#2639E9', '#F76E6C', '#FE7715']
... )

说明

图表展示内容:
  • 横轴:系数估计值 (Weight Estimates)

  • 纵轴:特征变量名称 (Variable)

  • 误差线:95% 置信区间

  • 垂直虚线:x=0 参考线

解释指南:
  • 误差线不跨越0:特征显著 (p<0.05)

  • 误差线跨越0:特征不显著 (p≥0.05)

  • 系数为正:特征与目标正相关

  • 系数为负:特征与目标负相关

hscredit.core.viz.plot_model_feature_importance(model, X, y=None, prediction_method='predict_proba', class_index=1, left_top_n=None, right_top_n=6, show_dependence=True, background_size=100, figsize=None, title=None, save=None, random_state=42, show=True, importance_source='raw', shap_by_label=True, hatch=True)[源代码]

绘制模型的 SHAP 特征重要性综合看板。

y 时,左侧叠加特征重要性柱状图与 SHAP 蜂群分布,右侧展示 Top N 特征的依赖关系。柱状图和 Top N 排序默认使用模型原生特征重要性,可通过 importance_source='shap' 改为平均绝对 SHAP 值;逻辑回归的模型重要性 使用系数绝对值。SHAP 模式默认按标签同时展示各组平均绝对 SHAP 柱条,设置 shap_by_label=False 可只展示全样本平均柱条。没有 y 时仅支持绘制 模型原生特征重要性。 prediction_method 决定 SHAP 解释的模型输出,可传 'predict''predict_score''predict_proba' 或接收 X 的 callable。

参数

参数:
  • model (Any) -- 已拟合模型

  • X (ndarray | DataFrame) -- 用于解释的特征矩阵

  • y (ndarray | Series | None) -- 真实标签;为 None 时仅绘制原生特征重要性

  • prediction_method (str | Callable[[ndarray | DataFrame], Any]) -- SHAP 使用的预测方法或 callable,默认 'predict_proba'

  • class_index (int) -- 二维预测结果中要解释的列索引,默认 1(正类)

  • left_top_n (int | None) -- 左侧显示特征数,默认 None,表示全部特征

  • right_top_n (int) -- 右侧依赖图显示特征数,默认 6

  • show_dependence (bool) -- 是否显示右侧依赖图,默认 True

  • background_size (int | None) -- SHAP 背景样本数,None 表示使用全部 X,默认 100

  • figsize (Tuple[float, float] | None) -- 画布大小;默认根据左右 Top N 自动计算

  • title (str | None) -- 总标题,默认包含模型名和预测方法

  • save (str | None) -- 图片保存路径,默认 None

  • random_state (int | None) -- 背景抽样和蜂群抖动随机种子,默认 42

  • show (bool) -- 是否调用 plt.show(),默认 True

  • importance_source (str) -- 重要性与 Top N 排序来源,可选 'raw'``(默认)或 ``'shap'

  • shap_by_label (bool) -- SHAP 模式是否按标签分别显示平均绝对 SHAP 柱条,默认 True

  • hatch (bool) -- 是否显示重要性柱斜线纹理,默认 True;标签 0/1 分别使用 /\

返回:

matplotlib Figure

参考样例

>>> from hscredit.core.viz import plot_model_feature_importance
>>> fig = plot_model_feature_importance(
...     model, X_test, y_test,
...     prediction_method='predict_proba',
...     left_top_n=None,
...     right_top_n=6,
...     importance_source='raw',
...     hatch=True,
... )
>>> fig.savefig('模型特征重要性.png', dpi=300, bbox_inches='tight')
hscredit.core.viz.plot_model_sample_shap(model, sample, background_data, prediction_method='predict_proba', class_index=1, background_size=100, max_display=None, value_precision=4, figsize=(14, 10), title=None, save=None, random_state=42, show=True)[源代码]

绘制单样本 SHAP 力图与瀑布图组合图。

上方直接复用 SHAP 原生 Matplotlib 力图展示全部字段如何把基准值推向当前 预测值,不经过整图栅格化或图片缩放;下方使用 SHAP 瀑布图按贡献绝对值 拆解同一结果。samplebackground_data 独立传入,避免把待解释 样本误当作背景分布。

参数

参数:
  • model (Any) -- 已拟合模型

  • sample (ndarray | Series | DataFrame) -- 单个待解释样本,可传 Series、单行 DataFrame、1D 或单行 ndarray

  • background_data (ndarray | DataFrame) -- SHAP 背景数据,必须是非空二维 DataFrame 或 ndarray

  • prediction_method (str | Callable[[ndarray | DataFrame], Any]) -- SHAP 使用的预测方法或 callable,默认 'predict_proba'

  • class_index (int) -- 二维模型或 SHAP 输出中要解释的列索引,默认 1(正类)

  • background_size (int | None) -- 背景抽样数,None 表示使用全部背景数据,默认 100

  • max_display (int | None) -- 瀑布图最大展示特征数,None 表示全部特征,默认 None

  • value_precision (int) -- 特征值、SHAP 贡献与输出刻度显示小数位数,默认 4

  • figsize (Tuple[float, float]) -- 组合图大小,默认 (14, 10)

  • title (str | None) -- 总标题,默认包含模型名和预测方法

  • save (str | None) -- 图片保存路径,默认 None

  • random_state (int | None) -- 背景抽样随机种子,默认 42

  • show (bool) -- 是否调用 plt.show(),默认 True

返回:

matplotlib Figure

参考样例

>>> from hscredit.core.viz import plot_model_sample_shap
>>> fig = plot_model_sample_shap(
...     model,
...     sample=X_test.iloc[0],
...     background_data=X_train,
...     max_display=None,
...     value_precision=4,
...     show=False,
... )
hscredit.core.viz.roc_plot(y_true, y_score, ax=None, figsize=(8, 8), title='ROC Curve', colors=None, show_auc=True, show_diagonal=True, label=None, save=None, **kwargs)[源代码]

绘制ROC曲线.

参数:
  • y_true (Series | ndarray) -- 真实标签

  • y_score (Series | ndarray) -- 预测概率分数

  • ax (Axes | None) -- matplotlib Axes对象,None时自动创建

  • figsize (Tuple[float, float]) -- 图像尺寸,默认(8, 8)

  • title (str) -- 图表标题

  • colors (List[str] | None) -- 配色方案

  • show_auc (bool) -- 是否显示AUC值

  • show_diagonal (bool) -- 是否显示对角线(随机猜测线)

  • label (str | None) -- 曲线标签(多模型对比时使用)

  • save (str | None) -- 保存路径

  • kwargs -- 其他参数传递给plt.plot

返回:

matplotlib Figure对象

返回类型:

Figure

参考样例

>>> fig = roc_plot(y_test, model.predict_proba(X_test)[:, 1])
>>>
>>> # 多模型对比
>>> fig, ax = plt.subplots(figsize=(8, 8))
>>> roc_plot(y_test, model1.predict_proba(X_test)[:, 1], ax=ax, label='Model A')
>>> roc_plot(y_test, model2.predict_proba(X_test)[:, 1], ax=ax, label='Model B')
hscredit.core.viz.pr_plot(y_true, y_score, ax=None, figsize=(8, 8), title='Precision-Recall Curve', colors=None, show_ap=True, show_baseline=True, label=None, save=None, **kwargs)[源代码]

绘制Precision-Recall曲线.

参数:
  • y_true (Series | ndarray) -- 真实标签

  • y_score (Series | ndarray) -- 预测概率分数

  • ax (Axes | None) -- matplotlib Axes对象

  • figsize (Tuple[float, float]) -- 图像尺寸,默认(8, 8)

  • title (str) -- 图表标题

  • colors (List[str] | None) -- 配色方案

  • show_ap (bool) -- 是否显示Average Precision

  • show_baseline (bool) -- 是否显示基线(随机猜测)

  • label (str | None) -- 曲线标签

  • save (str | None) -- 保存路径

  • kwargs -- 其他参数

返回:

matplotlib Figure对象

返回类型:

Figure

参考样例

>>> fig = pr_plot(y_test, model.predict_proba(X_test)[:, 1])
hscredit.core.viz.lift_plot(y_true, y_score, n_bins=10, ax=None, figsize=(10, 6), title='Lift 提升图', colors=None, show_baseline=True, save=None, **kwargs)[源代码]

绘制Lift提升图.

Lift = (该分箱坏样本率) / (整体坏样本率)

参数:
  • y_true (Series | ndarray) -- 真实标签

  • y_score (Series | ndarray) -- 预测概率分数

  • n_bins (int) -- 分箱数,默认10

  • ax (Axes | None) -- matplotlib Axes对象

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str) -- 图表标题

  • colors (List[str] | None) -- 配色方案

  • show_baseline (bool) -- 是否显示基线(Lift=1)

  • save (str | None) -- 保存路径

  • kwargs -- 其他参数

返回:

matplotlib Figure对象

返回类型:

Figure

参考样例

>>> fig = lift_plot(y_test, model.predict_proba(X_test)[:, 1], n_bins=10)
hscredit.core.viz.gain_plot(y_true, y_score, n_bins=10, ax=None, figsize=(10, 6), title='Cumulative Gain Chart', colors=None, show_baseline=True, save=None, **kwargs)[源代码]

绘制累积Gain增益图.

Gain表示捕获的坏样本比例。

参数:
  • y_true (Series | ndarray) -- 真实标签

  • y_score (Series | ndarray) -- 预测概率分数

  • n_bins (int) -- 分箱数,默认10

  • ax (Axes | None) -- matplotlib Axes对象

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str) -- 图表标题

  • colors (List[str] | None) -- 配色方案

  • show_baseline (bool) -- 是否显示基线(随机模型)

  • save (str | None) -- 保存路径

  • kwargs -- 其他参数

返回:

matplotlib Figure对象

返回类型:

Figure

参考样例

>>> fig = gain_plot(y_test, model.predict_proba(X_test)[:, 1], n_bins=10)
hscredit.core.viz.confusion_matrix_plot(y_true, y_pred, ax=None, figsize=(8, 6), title='混淆矩阵', cmap=None, normalize=None, show_values=True, show_metrics=True, save=None, **kwargs)[源代码]

绘制混淆矩阵热力图.

参数:
  • y_true (Series | ndarray) -- 真实标签

  • y_pred (Series | ndarray) -- 预测标签

  • ax (Axes | None) -- matplotlib Axes对象

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str) -- 图表标题

  • cmap (Any | None) -- 颜色映射

  • normalize (str | None) -- 归一化方式,None/'true'/'pred'/'all'

  • show_values (bool) -- 是否显示数值

  • show_metrics (bool) -- 是否显示评估指标

  • save (str | None) -- 保存路径

  • kwargs -- 其他参数

返回:

matplotlib Figure对象

返回类型:

Figure

参考样例

>>> fig = confusion_matrix_plot(y_test, y_pred)
>>> fig = confusion_matrix_plot(y_test, y_pred, normalize='true')
hscredit.core.viz.calibration_plot(y_true, y_score, n_bins=10, ax=None, figsize=(8, 8), title='校准曲线', colors=None, show_histogram=True, save=None, **kwargs)[源代码]

绘制校准曲线(可靠性图).

评估模型预测概率的可靠性。

参数:
  • y_true (Series | ndarray) -- 真实标签

  • y_score (Series | ndarray) -- 预测概率分数

  • n_bins (int) -- 分箱数,默认10

  • ax (Axes | None) -- matplotlib Axes对象

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str) -- 图表标题

  • colors (List[str] | None) -- 配色方案

  • show_histogram (bool) -- 是否显示样本分布直方图

  • save (str | None) -- 保存路径

  • kwargs -- 其他参数

返回:

matplotlib Figure对象

返回类型:

Figure

参考样例

>>> fig = calibration_plot(y_test, model.predict_proba(X_test)[:, 1])
hscredit.core.viz.score_dist_plot(df, score_col=None, target_col=None, ax=None, figsize=(12, 6), title=None, colors=None, n_bins=30, kde=True, show_stats=True, save=None, **kwargs)[源代码]

绘制评分分布对比图(好/坏样本分布对比).

参数:
  • df (DataFrame | Series) -- 数据DataFrame

  • score_col (str | None) -- 评分列名

  • target_col (str | None) -- 目标变量列名,None时不区分好坏

  • ax (Axes | None) -- matplotlib Axes对象

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str | None) -- 图表标题

  • colors (List[str] | None) -- 配色方案

  • n_bins (int) -- 直方图分箱数

  • kde (bool) -- 是否显示核密度估计曲线

  • show_stats (bool) -- 是否显示统计信息

  • save (str | None) -- 保存路径

  • kwargs -- 其他参数

返回:

matplotlib Figure对象

返回类型:

Figure

参考样例

>>> fig = score_dist_plot(df, 'score', 'target')
hscredit.core.viz.score_bin_plot(df, score_col, target_col, n_bins=10, bin_type='quantile', ax=None, figsize=(12, 6), title=None, colors=None, show_table=True, save=None, **kwargs)[源代码]

绘制评分分箱效果图(分箱区间+坏样本率).

使用 bin_plot(横向) + dataframe_plot 实现。

参数:
  • df (DataFrame) -- 数据DataFrame

  • score_col (str) -- 评分列名

  • target_col (str) -- 目标变量列名

  • n_bins (int) -- 分箱数,默认10

  • bin_type (str) -- 分箱方式,'quantile'(等频)或'uniform'(等宽)

  • ax (Axes | None) -- matplotlib Axes对象

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str | None) -- 图表标题

  • colors (List[str] | None) -- 配色方案

  • show_table (bool) -- 是否显示数据表格

  • save (str | None) -- 保存路径

  • kwargs -- 其他参数

返回:

matplotlib Figure对象

返回类型:

Figure

参考样例

>>> fig = score_bin_plot(df, 'score', 'target', n_bins=10)
hscredit.core.viz.threshold_analysis_plot(y_true, y_score, thresholds=None, ax=None, figsize=(12, 8), title='Threshold Analysis', colors=None, metrics=['precision', 'recall', 'f1', 'approval_rate'], save=None, **kwargs)[源代码]

绘制决策阈值分析图.

展示不同阈值下的各项评估指标,帮助选择最优决策阈值。

参数:
  • y_true (Series | ndarray) -- 真实标签

  • y_score (Series | ndarray) -- 预测概率分数

  • thresholds (ndarray | None) -- 阈值数组,None时自动生成

  • ax (Axes | None) -- matplotlib Axes对象

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str) -- 图表标题

  • colors (List[str] | None) -- 配色方案

  • metrics (List[str]) -- 要显示的指标列表

  • save (str | None) -- 保存路径

  • kwargs -- 其他参数

返回:

matplotlib Figure对象

返回类型:

Figure

参考样例

>>> fig = threshold_analysis_plot(y_test, y_score)
hscredit.core.viz.strategy_compare_plot(strategies, ax=None, figsize=(12, 8), title='Strategy Comparison', colors=None, metrics=['approval_rate', 'bad_rate', 'ks'], save=None, **kwargs)[源代码]

绘制多策略效果对比图.

参数:
  • strategies (List[Dict[str, Any]]) -- 策略列表,每项为包含策略指标的字典 例如: [{'name': '策略A', 'approval_rate': 0.8, 'bad_rate': 0.05, 'ks': 0.45}, ...]

  • ax (Axes | None) -- matplotlib Axes对象

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str) -- 图表标题

  • colors (List[str] | None) -- 配色方案

  • metrics (List[str]) -- 要对比的指标

  • save (str | None) -- 保存路径

  • kwargs -- 其他参数

返回:

matplotlib Figure对象

返回类型:

Figure

参考样例

>>> strategies = [
...     {'name': 'Current', 'approval_rate': 0.75, 'bad_rate': 0.08, 'ks': 0.40},
...     {'name': 'New', 'approval_rate': 0.80, 'bad_rate': 0.06, 'ks': 0.50}
... ]
>>> fig = strategy_compare_plot(strategies)
hscredit.core.viz.vintage_plot(df, mob_col, target_col, vintage_col=None, ax=None, figsize=(14, 8), title=None, colors=None, max_mob=None, show_heatmap=False, save=None, **kwargs)[源代码]

绘制Vintage账龄曲线图.

展示不同放款月份的资产在不同账龄(MOB)时的逾期率表现。

参数:
  • df (DataFrame) -- 数据DataFrame

  • mob_col (str) -- MOB(账龄)列名

  • target_col (str) -- 目标变量列名(逾期标识)

  • vintage_col (str | None) -- 放款月份/批次列名,None时不区分批次

  • ax (Axes | None) -- matplotlib Axes对象

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str | None) -- 图表标题

  • colors (List[str] | None) -- 配色方案

  • max_mob (int | None) -- 最大MOB显示值

  • show_heatmap (bool) -- 是否同时显示热力图

  • save (str | None) -- 保存路径

  • kwargs -- 其他参数

返回:

matplotlib Figure对象

返回类型:

Figure

参考样例

>>> fig = vintage_plot(df, 'mob', 'ever_dpd30', 'issue_month')
hscredit.core.viz.feature_importance_plot(features, importance, ax=None, figsize=(10, 8), title='Feature Importance', colors=None, top_n=20, horizontal=True, show_values=True, save=None, **kwargs)[源代码]

绘制特征重要性图.

参数:
  • features (List[str]) -- 特征名称列表

  • importance (List[float] | ndarray) -- 特征重要性值列表

  • ax (Axes | None) -- matplotlib Axes对象

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str) -- 图表标题

  • colors (List[str] | None) -- 配色方案

  • top_n (int | None) -- 显示前N个特征,None时显示全部

  • horizontal (bool) -- 是否水平显示

  • show_values (bool) -- 是否显示数值

  • save (str | None) -- 保存路径

  • kwargs -- 其他参数

返回:

matplotlib Figure对象

返回类型:

Figure

参考样例

>>> features = ['age', 'income', 'score', ...]
>>> importance = model.feature_importances_
>>> fig = feature_importance_plot(features, importance, top_n=15)
hscredit.core.viz.approval_rate_trend_plot(df, date_col, decision_col=None, score_col=None, threshold=None, freq='M', ax=None, figsize=(14, 6), title=None, colors=None, show_bad_rate=True, target_col=None, save=None, **kwargs)[源代码]

绘制审批通过率趋势图.

参数:
  • df (DataFrame) -- 数据DataFrame

  • date_col (str) -- 日期列名

  • decision_col (str | None) -- 决策结果列名(通过/拒绝),None时使用score_col+threshold

  • score_col (str | None) -- 评分列名(用于计算通过/拒绝)

  • threshold (float | None) -- 通过阈值(分数>=threshold为通过)

  • freq (str) -- 时间频率,'D'/'W'/'M'/'Q'

  • ax (Axes | None) -- matplotlib Axes对象

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str | None) -- 图表标题

  • colors (List[str] | None) -- 配色方案

  • show_bad_rate (bool) -- 是否同时显示逾期率趋势

  • target_col (str | None) -- 目标变量列名(show_bad_rate=True时需要)

  • save (str | None) -- 保存路径

  • kwargs -- 其他参数

返回:

matplotlib Figure对象

返回类型:

Figure

参考样例

>>> fig = approval_rate_trend_plot(df, 'apply_date', decision_col='is_approved')
>>> fig = approval_rate_trend_plot(df, 'apply_date', score_col='score', threshold=500)
hscredit.core.viz.bad_rate_trend_plot(df, date_col, target=None, overdue=None, dpds=None, del_grey=False, dimension_col=None, freq='M', ax=None, figsize=(14, 6), title=None, colors=None, show_sample_count=True, save=None, **kwargs)[源代码]

绘制坏样本率趋势图(支持分维度和多逾期标签展示).

参数:
  • df (DataFrame) -- 数据DataFrame

  • date_col (str) -- 日期列名

  • target (str | None) -- 目标变量列名(单标签模式)

  • overdue (str | List[str] | None) -- 逾期天数字段名或列表,优先于 target

  • dpds (int | List[int] | None) -- 逾期定义天数或列表,与 overdue 配合生成标签

  • del_grey (bool) -- 是否排除逾期天数在 (0, dpd] 区间的灰样本

  • dimension_col (str | None) -- 维度列名(如客户等级),None时不分维度

  • freq (str) -- 时间频率,'D'/'W'/'M'/'Q'

  • ax (Axes | None) -- matplotlib Axes对象

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str | None) -- 图表标题

  • colors (List[str] | None) -- 配色方案

  • show_sample_count (bool) -- 是否显示样本数柱状图

  • save (str | None) -- 保存路径

  • kwargs -- 其他参数

返回:

matplotlib Figure对象

返回类型:

Figure

参考样例

>>> fig = bad_rate_trend_plot(df, 'apply_date', target='target')
>>> fig = bad_rate_trend_plot(df, 'apply_date', overdue='MOB1', dpds=[7, 30])
hscredit.core.viz.metric_comparison_plot(data, label_col, value_col, horizontal=True, sort_values=False, ascending=True, color_scheme=None, reference_lines=None, value_format='{:.3f}', ax=None, figsize=(10, 6), title=None, xlabel=None, ylabel=None, save=None, **kwargs)[源代码]

绘制指标对比柱状图.

适用于已经完成统计的 IV、PSI、特征重要性、模型评分等结果表。

参数:
  • data (DataFrame) -- 指标结果表

  • label_col (str) -- 分类标签列名

  • value_col (str) -- 指标数值列名

  • horizontal (bool) -- 是否绘制横向柱状图

  • sort_values (bool) -- 是否按指标值排序

  • ascending (bool) -- 排序方向

  • color_scheme (str | None) -- 语义配色,可选 'iv''psi'

  • reference_lines (List[Tuple[float, str, str]] | None) -- 参考线列表,每项为 (数值, 标签, 颜色)

  • value_format (str) -- 数值标签格式

  • ax (Axes | None) -- matplotlib Axes

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str | None) -- 图标题

  • xlabel (str | None) -- 横轴标题

  • ylabel (str | None) -- 纵轴标题

  • save (str | None) -- 保存路径

返回:

matplotlib Figure

返回类型:

Figure

参考样例

>>> fig = metric_comparison_plot(iv_table, '特征', 'IV', color_scheme='iv')
hscredit.core.viz.variable_iv_plot(df, features, target, top_n=20, ax=None, figsize=(12, 8), title='特征IV值排名', save=None, **kwargs)[源代码]

特征IV值横向柱状图.

按IV降序排列,标注IV阈值参考线(0.02 / 0.10 / 0.30)。

参数:
  • df (DataFrame) -- 数据集

  • features (List[str]) -- 特征列表

  • target (str) -- 目标变量列名

  • top_n (int) -- 显示前N个特征,默认20

  • ax (Axes | None) -- matplotlib Axes,None时自动创建

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str) -- 图标题

  • save (str | None) -- 保存路径,None时不保存

返回:

matplotlib Figure

返回类型:

Figure

参考样例

>>> fig = variable_iv_plot(df, features=df.columns.tolist(), target='fpd30')
hscredit.core.viz.variable_woe_trend_plot(bin_table, feature=None, ax=None, figsize=(10, 5), title=None, save=None, **kwargs)[源代码]

WOE折线图 + 坏率柱状图(双轴).

用于模型报告变量分析,展示每个分箱的WOE值和坏样本率。

参数:
  • bin_table (DataFrame) -- 分箱统计表,需含「分箱标签」/「WOE」/「坏样本率」列 (兼容 OptimalBinning.get_bin_table() 输出)

  • feature (str | None) -- 特征名,用于标题

  • ax (Axes | None) -- matplotlib Axes

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str | None) -- 图标题,None时自动生成

  • save (str | None) -- 保存路径

返回:

Figure

返回类型:

Figure

参考样例

>>> binner = OptimalBinning().fit(df[['age']], df['fpd30'])
>>> tbl = binner.get_bin_table()['age']
>>> fig = variable_woe_trend_plot(tbl, feature='age')
hscredit.core.viz.variable_psi_heatmap(psi_matrix, ax=None, figsize=(14, 8), title='特征PSI热力图', save=None, **kwargs)[源代码]

特征PSI矩阵热力图.

颜色反映偏移程度:低 PSI 使用主题冷色,高 PSI 使用粉红风险色。

参数:
  • psi_matrix (DataFrame) -- PSI矩阵,行=特征,列=时间周期或数据集,格=PSI值

  • ax (Axes | None) -- matplotlib Axes

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str) -- 图标题

  • save (str | None) -- 保存路径

返回:

Figure

返回类型:

Figure

参考样例

>>> psi_mat = batch_psi_analysis(df_train, df_test, features)
>>> fig = variable_psi_heatmap(psi_mat)
hscredit.core.viz.variable_importance_grouped_plot(importance_df, feature_col='feature', value_col='importance', group_col='category', top_n=30, ax=None, figsize=(12, 8), title='特征重要性(分类)', save=None, **kwargs)[源代码]

按特征类别分组的重要性横向柱状图.

参数:
  • importance_df (DataFrame) -- 特征重要性 DataFrame,需含 feature_col 和 value_col 列

  • feature_col (str) -- 特征名列名,默认 'feature'

  • value_col (str) -- 重要性值列名,默认 'importance'

  • group_col (str | None) -- 分组列名,默认 'category';None 时不分组

  • top_n (int) -- 显示前N个,默认30

  • ax (Axes | None) -- matplotlib Axes

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str) -- 图标题

  • save (str | None) -- 保存路径

返回:

Figure

返回类型:

Figure

参考样例

>>> imp_df = pd.DataFrame({'feature': feats, 'importance': imps, 'category': cats})
>>> fig = variable_importance_grouped_plot(imp_df)
hscredit.core.viz.variable_missing_badrate_plot(df, features, target, ax=None, figsize=(10, 7), title='缺失率 vs 坏账率(缺失样本)', save=None, **kwargs)[源代码]

缺失率 vs 坏账率散点图.

横轴=特征缺失率,纵轴=缺失样本坏账率。 用于评估缺失值是否携带信息(坏率显著异于总体则说明缺失本身有预测价值)。

参数:
  • df (DataFrame) -- 数据集

  • features (List[str]) -- 特征列表

  • target (str) -- 目标变量列名

  • ax (Axes | None) -- matplotlib Axes

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str) -- 图标题

  • save (str | None) -- 保存路径

返回:

Figure

返回类型:

Figure

参考样例

>>> fig = variable_missing_badrate_plot(df, features=feats, target='fpd30')
hscredit.core.viz.score_ks_plot(y_true=None, y_prob=None, datasets=None, ax=None, figsize=(10, 6), title='KS曲线', save=None, **kwargs)[源代码]

KS曲线图,支持多数据集叠加.

参数:
  • y_true -- 真实标签(单数据集时使用)

  • y_prob -- 预测概率(单数据集时使用)

  • datasets (Dict[str, Tuple] | None) -- {'训练集': (y_true, y_prob), '测试集': ...}

  • ax -- matplotlib Axes

  • figsize -- 图像尺寸

  • title (str) -- 图标题

  • save (str | None) -- 保存路径

返回:

Figure

返回类型:

Figure

参考样例

>>> fig = score_ks_plot(y_test, proba)
>>> fig = score_ks_plot(datasets={'训练集': (y_tr, p_tr), '测试集': (y_te, p_te)})
hscredit.core.viz.score_distribution_comparison_plot(scores, ax=None, figsize=(10, 5), title='评分分布对比', bins=50, save=None, **kwargs)[源代码]

多数据集评分分布对比图(KDE + 直方图).

参数:
  • scores (Dict[str, ndarray | Series]) -- {'训练集': score_array, '测试集': score_array}

  • ax -- matplotlib Axes

  • figsize -- 图像尺寸

  • title (str) -- 图标题

  • bins (int) -- 直方图分箱数

  • save (str | None) -- 保存路径

返回:

Figure

返回类型:

Figure

参考样例

>>> fig = score_distribution_comparison_plot({'训练集': s_tr, '测试集': s_te})
hscredit.core.viz.score_badrate_bin_plot(y_true, score, n_bins=10, ax=None, figsize=(12, 6), title='评分分箱坏率', save=None, **kwargs)[源代码]

评分分箱坏率图:柱=样本量,折线=坏率.

参数:
  • y_true -- 真实标签

  • score -- 评分

  • n_bins (int) -- 分箱数,默认10

  • ax -- matplotlib Axes

  • figsize -- 图像尺寸

  • title (str) -- 图标题

  • save (str | None) -- 保存路径

返回:

Figure

返回类型:

Figure

参考样例

>>> fig = score_badrate_bin_plot(y_test, model.predict_score(X_test))
hscredit.core.viz.score_lift_plot(y_true=None, y_prob=None, ratios=None, datasets=None, ax=None, figsize=(10, 6), title='LIFT曲线', save=None, **kwargs)[源代码]

LIFT曲线图,支持多数据集叠加,标注关键点.

参数:
  • y_true -- 真实标签(单数据集)

  • y_prob -- 预测概率(单数据集)

  • ratios (List[float]) -- 覆盖率列表,默认 [0.01,0.03,0.05,0.10,0.20,0.30,0.50]

  • datasets (Dict[str, Tuple] | None) -- {'训练集': (y_true, y_prob), ...}

  • ax -- matplotlib Axes

  • figsize -- 图像尺寸

  • title (str) -- 图标题

  • save (str | None) -- 保存路径

返回:

Figure

返回类型:

Figure

参考样例

>>> fig = score_lift_plot(y_test, proba)
hscredit.core.viz.score_approval_badrate_curve(y_true, score, score_ascending=True, n_points=100, ax=None, figsize=(10, 6), title='通过率 - 坏率权衡曲线', save=None, **kwargs)[源代码]

审批通过率 vs 坏账率曲线(策略人员必备).

参数:
  • y_true -- 真实标签

  • score -- 评分

  • score_ascending (bool) -- True=分数越高越安全(低分拒绝)

  • n_points (int) -- 曲线采样点数

  • ax -- matplotlib Axes

  • figsize -- 图像尺寸

  • title (str) -- 图标题

  • save (str | None) -- 保存路径

返回:

Figure

返回类型:

Figure

参考样例

>>> fig = score_approval_badrate_curve(y_test, model.predict_score(X_test))
hscredit.core.viz.rule_swap_plot(pipeline, rule_categories=None, figsize=(15, 5), title='规则置换分析', save=None, **kwargs)[源代码]

绘制规则置换分析三联图.

三个面板依次展示规则命中样本数、LIFT 值和策略通过率变化。

参数:
  • pipeline (DataFrame) -- 规则置换流程明细表,通常来自 rule_swap_analysis()swap_pipeline, 需含 规则分类 / 样本总数 / 坏样本率 / LIFT值 / 通过率(绝对值)

  • rule_categories (List[str] | None) -- 参与对比的规则分类,默认 ['OUT-OUT拒绝', 'IN-OUT置出', 'OUT-IN置入']

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str) -- 总标题

  • save (str | None) -- 保存路径

返回:

matplotlib Figure

返回类型:

Figure

参考样例

>>> from hscredit.report import rule_swap_analysis
>>> from hscredit.core.viz import rule_swap_plot
>>> res = rule_swap_analysis(data, score='score', rules_in=[r], reference_data=hist, target='FPD')
>>> rule_swap_plot(res['swap_pipeline'], title='策略置换分析')
hscredit.core.viz.strategy_simulation_plot(simulation, threshold_col='评分阈值', approval_col='通过率(%)', bad_rate_col='通过人群坏率(%)', ax=None, figsize=(10, 5), title='评分阈值策略仿真', save=None, **kwargs)[源代码]

绘制候选评分阈值的通过率与坏率双轴图.

参数:
  • simulation (DataFrame) -- 策略仿真结果表

  • threshold_col (str) -- 评分阈值列名

  • approval_col (str) -- 通过率列名,数值单位为百分数

  • bad_rate_col (str) -- 通过人群坏率列名,数值单位为百分数

  • ax -- matplotlib Axes

  • figsize (Tuple[float, float]) -- 图像尺寸

  • title (str) -- 图标题

  • save (str | None) -- 保存路径

返回:

matplotlib Figure

返回类型:

Figure

参考样例

>>> import pandas as pd
>>> from hscredit.core.viz import strategy_simulation_plot
>>> sim = pd.DataFrame({
...     '评分阈值': [500, 550, 600, 650],
...     '通过率(%)': [90, 75, 55, 35],
...     '通过人群坏率(%)': [6.0, 4.5, 3.0, 2.0],
... })
>>> strategy_simulation_plot(sim)
hscredit.core.viz.feature_trend_by_time(df, feature, date_col, target=None, stat='mean', freq='M', ax=None, figsize=(12, 5), title=None, save=None, **kwargs)[源代码]

特征随时间的统计趋势图,检测特征偏移.

参数:
  • df (DataFrame) -- 数据集

  • feature (str) -- 特征列名

  • date_col (str) -- 日期列名

  • target (str | None) -- 目标变量(stat='badrate'时必需)

  • stat (str) -- 'mean'/'median'/'psi'/'badrate'

  • freq (str) -- 'M'月/'Q'季/'W'周

  • ax -- matplotlib Axes

  • figsize -- 图像尺寸

  • title (str | None) -- 图标题

  • save (str | None) -- 保存路径

返回:

Figure

返回类型:

Figure

参考样例

>>> fig = feature_trend_by_time(df, 'age', 'apply_date', stat='mean')
hscredit.core.viz.feature_drift_comparison(df_base, df_target, features, top_n=20, ax=None, figsize=(12, 8), title='特征分布偏移(PSI)', save=None, **kwargs)[源代码]

多特征偏移瀑布图:颜色标注偏移等级.

参数:
  • df_base (DataFrame) -- 基准数据集(训练集)

  • df_target (DataFrame) -- 目标数据集(测试集/OOT)

  • features (List[str]) -- 待分析特征列表

  • top_n (int) -- 按PSI降序显示前N个

  • ax -- matplotlib Axes

  • figsize -- 图像尺寸

  • title (str) -- 图标题

  • save (str | None) -- 保存路径

返回:

Figure

返回类型:

Figure

参考样例

>>> fig = feature_drift_comparison(df_train, df_oot, model_features)
hscredit.core.viz.feature_effectiveness_by_segment(df, feature, target, segment_col, metric='iv', ax=None, figsize=(10, 6), title=None, save=None, **kwargs)[源代码]

特征在不同客群下的有效性对比柱状图.

参数:
  • df (DataFrame) -- 数据集

  • feature (str) -- 特征列名

  • target (str) -- 目标变量列名

  • segment_col (str) -- 客群列名

  • metric (str) -- 'iv' / 'ks' / 'auc'

  • ax -- matplotlib Axes

  • figsize -- 图像尺寸

  • title (str | None) -- 图标题

  • save (str | None) -- 保存路径

返回:

Figure

返回类型:

Figure

参考样例

>>> fig = feature_effectiveness_by_segment(df, 'age', 'fpd30', 'channel')
hscredit.core.viz.feature_cross_heatmap(df, feature_x, feature_y, target, stat='badrate', n_bins=5, ax=None, figsize=(10, 8), title=None, save=None, **kwargs)[源代码]

两特征交叉分析热力图:行=feature_x,列=feature_y,格=坏率/样本数/LIFT.

参数:
  • df (DataFrame) -- 数据集

  • feature_x (str) -- 行特征

  • feature_y (str) -- 列特征

  • target (str) -- 目标变量

  • stat (str) -- 'badrate'/'count'/'lift'

  • n_bins (int) -- 数值型特征分箱数

  • ax -- matplotlib Axes

  • figsize -- 图像尺寸

  • title (str | None) -- 图标题

  • save (str | None) -- 保存路径

返回:

Figure

返回类型:

Figure

参考样例

>>> fig = feature_cross_heatmap(df, 'age', 'income', 'fpd30')
hscredit.core.viz.population_drift_monitor(df_list, labels, features, target=None, top_n_drift=5, figsize=(14, 10), title='客群偏移监控', save=None, **kwargs)[源代码]

多期客群偏移监控大图(PSI热力图 + 趋势折线).

参数:
  • df_list (List[DataFrame]) -- 多期数据集列表(第一期为基准)

  • labels (List[str]) -- 各期标签

  • features (List[str]) -- 特征列表

  • target (str | None) -- 目标变量(可选)

  • top_n_drift (int) -- 偏移最大的Top N特征

  • figsize -- 图像尺寸

  • title (str) -- 图标题

  • save (str | None) -- 保存路径

返回:

Figure

返回类型:

Figure

参考样例

>>> fig = population_drift_monitor([df1,df2,df3], ['Q1','Q2','Q3'], feats)
hscredit.core.viz.segment_scorecard_comparison(df, score_col, target, segment_col, metrics=None, ax=None, figsize=(14, 6), title='分客群评分效果对比', save=None, **kwargs)[源代码]

按客群分组的评分指标对比柱状图.

每个指标单独一个子图,对比 同一指标在不同客群下的差异 (各指标量纲不同, 分子图展示可避免 KS/AUC/LIFT 因量纲差异而无法横向比较)。

参数:
  • df (DataFrame) -- 数据集

  • score_col (str) -- 评分列名

  • target (str) -- 目标变量列名

  • segment_col (str) -- 客群列名

  • metrics (List[str]) -- 展示指标,默认 ['KS','AUC','LIFT@10%']

  • ax -- matplotlib Axes(仅单指标时生效;多指标时自动创建子图)

  • figsize -- 图像尺寸

  • title (str) -- 图标题

  • save (str | None) -- 保存路径

返回:

Figure

返回类型:

Figure

参考样例

>>> fig = segment_scorecard_comparison(df, 'score', 'fpd30', 'channel')
class hscredit.core.viz.DecisionTreeViz(backend='matplotlib', feature_names=None, title='', figsize=(18, 12), dpi=240, **kwargs)[源代码]

基类:object

AntV G6 风格决策树可视化器。

支持 matplotlib / pyecharts / graphviz 三种渲染后端, 统一 API 设计,按需切换。

参数

参数:
  • backend (str) -- 渲染后端,可选 'matplotlib' | 'pyecharts' | 'graphviz' - 'matplotlib': 纯 Python,无需额外依赖,适合快速预览 - 'pyecharts': 交互式 HTML,支持 tooltip、缩放 - 'graphviz': 高质量矢量图,适合报告嵌入

  • feature_names (List[str] | None) -- 特征名列表(当 tree_obj 为 sklearn clf 时需要)

  • title (str) -- 图表标题

  • figsize (Tuple[float, float]) -- matplotlib 画布大小

  • dpi (int) -- matplotlib 分辨率

参考样例

>>> # matplotlib 快速预览
>>> viz = DecisionTreeViz(backend='matplotlib')
>>> fig = viz.plot(ext, save='tree.png')
>>> plt.show()
>>> # pyecharts 交互式
>>> viz = DecisionTreeViz(backend='pyecharts')
>>> chart = viz.plot(ext)
>>> chart.render('tree.html')
>>> # graphviz 高质量
>>> viz = DecisionTreeViz(backend='graphviz')
>>> src = viz.plot(ext, save='tree.pdf')
SUPPORTED_BACKENDS = ['matplotlib', 'pyecharts', 'graphviz']
plot(tree_obj, save=None, title=None, **kwargs)[源代码]

绘制决策树。

参数:
  • tree_obj (Any) -- ManualTreeExtractor 或 sklearn DecisionTreeClassifier

  • save (str | None) -- 保存路径

  • title (str | None) -- 图表标题(覆盖构造时的 title)

返回:

渲染结果(matplotlib Figure / pyecharts Chart / graphviz Source)

返回类型:

Any

render(path)[源代码]

保存/渲染当前树图到文件。

参数:

path (str) -- 保存路径

返回:

渲染结果

返回类型:

Any

hscredit.core.viz.plot_tree(tree_obj, backend='matplotlib', save=None, **kwargs)[源代码]

便捷函数:一行命令绘制决策树。

参数

参数:
  • tree_obj (Any) -- ManualTreeExtractor 或 sklearn DecisionTreeClassifier

  • backend (str) -- 渲染后端,默认 'matplotlib'

  • save (str | None) -- 保存路径

  • kwargs -- 传给 DecisionTreeViz 的参数

返回:

渲染结果

返回类型:

Any

参考样例

>>> # matplotlib
>>> fig = plot_tree(ext, backend='matplotlib', save='tree.png')
>>> # pyecharts
>>> chart = plot_tree(ext, backend='pyecharts', save='tree.html')
>>> # graphviz
>>> src = plot_tree(ext, backend='graphviz', save='tree.pdf')
hscredit.core.viz.plot_tree_matplotlib(tree_obj, figsize=(18, 12), dpi=150, save=None, title='', show_stats=True, show_gini=True, node_color_scheme='risk', feature_names=None)[源代码]

使用 matplotlib 绘制 AntV G6 风格的决策树。

AntV G6 风格特点: - 卡片式节点:圆角矩形,内含标题、统计信息 - 平滑曲线连线:子节点从父节点底部中点出发 - 颜色语义:按坏账率从浅蓝→浅红渐变

参数

参数:
  • tree_obj (Any) -- ManualTreeExtractor 或 sklearn DecisionTreeClassifier

  • figsize (Tuple[float, float]) -- 初始画布大小(宽, 高),单位英寸;实际画布会按节点统一宽度/树形结构 自动重新计算并覆盖该值,以保证 1 个数据坐标单位严格等于 1 inch(否则节点框 与文字字号的相对比例会被意外缩放,导致文字溢出节点)

  • dpi (int) -- 图像分辨率

  • save (str | None) -- 保存路径(如 'tree.png'),如传入路径中有文件夹不存在,会自动创建,默认 None

  • title (str) -- 图表标题

  • show_stats (bool) -- 是否显示节点统计信息(样本数、坏账率等)

  • show_gini (bool) -- 是否显示 Gini 不纯度

  • node_color_scheme (str) -- 配色方案,'risk'=按坏账率,'depth'=按深度

  • feature_names (List[str] | None)

返回:

matplotlib Figure 对象

返回类型:

Figure

参考样例

>>> fig = plot_tree_matplotlib(ext, figsize=(20, 14), dpi=200)
>>> plt.show()
>>> fig.savefig('tree.png', dpi=200, bbox_inches='tight')
hscredit.core.viz.plot_tree_pyecharts(tree_obj, figsize=None, dpi=100, title='', width=None, height=None, save=None, page_title='决策树可视化', feature_names=None)[源代码]

使用 pyecharts 绘制 AntV G6 风格的交互式决策树。

交互功能: - 鼠标悬停 tooltip 显示节点详细信息 - 支持缩放和平移 - 可导出为 HTML

参数

参数:
  • tree_obj (Any) -- ManualTreeExtractor 或 sklearn DecisionTreeClassifier

  • figsize (Tuple[float, float] | None) -- 画布尺寸(宽, 高),单位英寸(与 plot_tree_matplotlib() 同名参数 对齐);最终像素 = figsize × dpi。默认 None 时回退到默认画布 1400×900 px

  • dpi (int) -- 每英寸像素数,与 figsize 配合换算画布像素尺寸,默认 100

  • title (str) -- 图表标题

  • width (str | None) -- 画布宽度(CSS 格式,如 '1400px');显式给出时优先于 figsize/dpi

  • height (str | None) -- 画布高度(CSS 格式);显式给出时优先于 figsize/dpi

  • save (str | None) -- 保存路径(如 'tree.html'),如传入路径中有文件夹不存在,会自动创建,默认 None

  • page_title (str) -- HTML 页面标题

  • feature_names (List[str] | None)

返回:

pyecharts Graph 对象

返回类型:

Any

参考样例

>>> chart = plot_tree_pyecharts(ext, figsize=(14, 9))
>>> chart.render('tree.html')
>>> chart.render_notebook()  # 在 Jupyter 中直接显示
hscredit.core.viz.plot_tree_graphviz(tree_obj, figsize=None, dpi=150, save=None, title='', feature_names=None)[源代码]

使用 graphviz 绘制 AntV G6 风格的高质量决策树。

样式与实现参考 plot_tree_matplotlib():圆形节点徽章 + 主题色标题栏 + 无表头两列指标表格,全树统一节点宽度(含上限,超长切分条件自动换行), 人工修改节点(is_manual)使用副主题色边框/标题/徽章,自其向下的连接线 也统一换为副主题色。卡片采用与 plot_tree_matplotlib() 一致的直角矩形。

特点: - 高质量矢量图(SVG/PDF/PNG) - 支持中文 - 适合嵌入报告

参数

参数:
  • tree_obj (Any) -- ManualTreeExtractor 或 sklearn DecisionTreeClassifier

  • figsize (Tuple[float, float] | None) -- 输出图像最大尺寸(宽, 高),单位英寸;graphviz 会在保持纵横比的 前提下将整张图缩放到不超过该尺寸(与 plot_tree_matplotlib() 同名参数 含义对齐)。默认 None 表示按内容自然尺寸输出(不缩放)

  • dpi (int) -- 图像分辨率(每英寸像素数),用于控制位图(png 等)输出的像素大小, 默认 150。配合 figsize 可灵活控制最终图片大小

  • save (str | None) -- 保存路径(如 'tree.png' / 'tree.pdf' / 'tree.svg'),渲染格式由文件名 后缀自动推断;如传入路径中有文件夹不存在,会自动创建,默认 None

  • title (str) -- 图表标题

  • feature_names (List[str] | None) -- 特征名列表(sklearn clf 推荐传入)

返回:

graphviz.Source 对象

返回类型:

Any

参考样例

>>> src = plot_tree_graphviz(ext, figsize=(12, 8), dpi=150, save='tree.pdf')
hscredit.core.viz.tree_leaf_comparison_plot(evaluations, overall_bad_rate, figsize=None, title='叶节点效果对比', save=None, **kwargs)[源代码]

对比多棵决策树的叶节点坏样本率与 LIFT.

参数:
  • evaluations (Dict[str, DataFrame]) -- {树名称: 叶节点评估表},表中需包含节点编号、坏样本率和LIFT值

  • overall_bad_rate (float) -- 总体坏样本率

  • figsize (Tuple[float, float] | None) -- 图像尺寸

  • title (str) -- 总标题

  • save (str | None) -- 保存路径

返回:

matplotlib Figure

hscredit.core.viz.setup_axis_style(ax, colors=None, hide_top_right=False)[源代码]

设置坐标轴样式.

参数:
  • ax -- matplotlib Axes 对象

  • colors (list | None) -- 边框颜色

  • hide_top_right (bool) -- 是否隐藏顶部和右侧边框

hscredit.core.viz.save_figure(fig, save_path=None, dpi=240)[源代码]

保存图表.

参数:
  • fig -- matplotlib Figure 对象

  • save_path (str | None) -- 保存路径(为 None 时不保存,直接返回);目录不存在时自动创建

  • dpi (int) -- 分辨率,默认 240

参考样例

>>> from hscredit.core.viz import save_figure
>>> save_figure(fig, 'output/分箱图.png', dpi=300)
hscredit.core.viz.get_or_create_ax(figsize=(10, 6), ax=None, return_fig=True)[源代码]

获取或创建 Axes 对象.

如果传入 ax,则直接使用;否则创建新的 Figure 和 Axes。

参数:
  • figsize (Tuple[float, float]) -- 图像尺寸(创建新图时使用)

  • ax (Any | None) -- 可选的 matplotlib Axes 对象

  • return_fig (bool) -- 是否返回 Figure 对象

返回:

如果 return_fig=True 返回 (fig, ax),否则返回 ax

返回类型:

Tuple[Any, ...]

参考样例

>>> # 方式1:自动创建新的 figure 和 ax
>>> fig, ax = get_or_create_ax(figsize=(10, 6))
>>>
>>> # 方式2:使用传入的 ax
>>> import matplotlib.pyplot as plt
>>> _, axes = plt.subplots(2, 3, figsize=(18, 10))
>>> for i, col in enumerate(features):
...     _, ax = get_or_create_ax(ax=axes[i])
...     # 绘图...
hscredit.core.viz.create_legend(fig_or_ax, loc='upper center', bbox_to_anchor=(0.5, 0.98), ncol=2, frameon=False, handles=None, labels=None)[源代码]

创建图例.

参数:
  • fig_or_ax -- Figure 或 Axes 对象

  • loc (str) -- 图例位置

  • bbox_to_anchor (Tuple[float, float]) -- 锚点位置

  • ncol (int) -- 列数

  • frameon (bool) -- 是否显示边框

  • handles (list | None) -- 图例句柄(可选)

  • labels (list | None) -- 图例标签(可选)

返回:

Legend 对象

hscredit.core.viz.format_bin_label(label, max_len=35)[源代码]

格式化分箱标签.

参数:
  • label (str) -- 原始标签

  • max_len (int) -- 最大长度

返回:

格式化后的标签

返回类型:

str

hscredit.core.viz.get_series_colors(n)[源代码]

获取 n 条数据系列的统一配色(主题色 + 副主题色 + 扩展色循环).

参数:

n (int) -- 需要的颜色数量

返回:

长度为 n 的颜色列表,优先使用主题色与副主题色,再循环扩展色板

返回类型:

list

hscredit.core.viz.get_psi_color(value)[源代码]

根据 PSI 取值返回统一语义色(用于稳定性图表着色)。

参数:

value (float) -- PSI 值

返回:

颜色十六进制字符串:

  • value < 0.10:稳定色(STABLE_COLOR)

  • 0.10 <= value < 0.25:变化色(CHANGING_COLOR)

  • value >= 0.25:不稳定色(UNSTABLE_COLOR)

返回类型:

str

hscredit.core.viz.make_colormap(name, colors=None, n=256)[源代码]

根据统一色板创建 matplotlib colormap.

参数:
  • name (str) -- colormap 名称

  • colors (list | None) -- 颜色列表,默认使用蓝紫粉红连续色阶

  • n (int) -- 颜色采样数

返回:

LinearSegmentedColormap

hscredit.core.viz.make_risk_cmap(name='hscredit_risk', n=256)[源代码]

创建风险连续色阶(低风险蓝紫 → 高风险粉红)。

参数:
  • name (str) -- colormap 名称,默认 "hscredit_risk"

  • n (int) -- 颜色采样数,默认 256

返回:

LinearSegmentedColormap,可直接传给热力图的 cmap 参数

hscredit.core.viz.make_diverging_cmap(name='hscredit_diverging', n=256)[源代码]

创建发散色阶(主题蓝 → 近白 → 副主题红),适合带正负/中心值的热力图。

参数:
  • name (str) -- colormap 名称,默认 "hscredit_diverging"

  • n (int) -- 颜色采样数,默认 256

返回:

LinearSegmentedColormap

hscredit.core.viz.set_style(theme='risk', chinese_font=True)[源代码]

设置全局可视化主题.

参数:
  • theme (str) -- 主题名称,可选 'risk'(默认风控主题), 'minimal'(极简), 'report'(报告用)

  • chinese_font (bool) -- 是否自动配置中文字体支持

抛出:

ValueError -- 未知主题名称

用法:

from hscredit.core.viz import set_style

set_style("risk")         # 标准风控主题
set_style("report")       # 报告导出主题(高DPI)
set_style("minimal")      # 极简主题
hscredit.core.viz.reset_style()[源代码]

重置为 hscredit.init_setting 定义的默认样式.

hscredit.core.viz.get_current_theme()[源代码]

获取当前已应用的主题名称.

返回类型:

str | None

hscredit.core.viz.get_palette(name='default')[源代码]

获取配色方案.

参数:

name (str) -- 方案名称,可选 'default'/'primary'(3色), 'extended', 'pink_purple', 'semantic'(语义色字典)

返回:

颜色列表或字典

hscredit.core.viz.get_font_sizes()[源代码]

获取字体大小层级.

返回类型:

Dict[str, int]

hscredit.core.viz.get_defaults()[源代码]

获取全局默认参数.

返回类型:

dict