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

如何对sns.jointplot的边际直方图进行归一化处理

解决Seaborn jointplot边际直方图归一化(显示占比)的问题

要把sns.jointplot的边际直方图从计数形式改为占比形式,只需在marginal_kws参数中添加stat='probability',这个参数会让直方图自动将每个bin的计数除以总样本数,得到占比(范围0到1)。

修改后的完整代码

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

sns.set(style='white')

# 生成样本数据
x = np.random.exponential(70, 100)
y = np.random.exponential(0.005, 100)

# 核心修改:在marginal_kws中加入stat='probability'实现归一化
g = sns.jointplot(x=x, y=y, xlim=[30, 800], ylim=[0.0007, 0.023], 
                  marker='*', s=10, color='k', ec='k',
                  marginal_kws=dict(bins=10, fill=True, log_scale=True, stat='probability'),
                  height=1, ratio=6, marginal_ticks=True)

g.plot_joint(sns.kdeplot, color="r", zorder=0, levels=10, fill=True, thresh=0.1)

# 自定义轴刻度为百分比(可选操作)
def to_percent(x, pos):
    return f'{x*100:.0f}%'

# 给x轴和y轴的边际直方图设置百分比刻度
g.ax_marg_x.yaxis.set_major_formatter(FuncFormatter(to_percent))
g.ax_marg_y.xaxis.set_major_formatter(FuncFormatter(to_percent))

# 原有绘图调整
g.ax_joint.invert_xaxis()
g.fig.set_size_inches(14,10)
g.ax_joint.axvline(x=70, color='red', ls='--', lw=2)
g.ax_joint.axvline(x=650, color='red', ls='--', lw=2)
g.ax_joint.axhline(y=0.005, color='red', ls='--', lw=2)

plt.show()

关键说明

  • stat='probability':这是实现归一化的核心参数,Seaborn的直方图会自动计算每个bin的占比(样本数/总样本数),替代原来的计数。
  • 百分比刻度格式化:通过FuncFormatter将0-1的占比转换为百分比显示,这是可选操作,如果不需要百分比,仅保留stat='probability'即可。
  • 原代码中的log_scale=True可以保留,它只影响轴的缩放方式,不改变归一化逻辑。

内容的提问来源于stack exchange,提问作者JohnGoodWill

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 23:06:25