如何修改Seaborn distplot的X轴组间距,自定义分组区间?
调整Seaborn直方图的X轴分组间距(0-50、50-100)
要把直方图X轴改成0-50、50-100的分组,核心是通过bins参数指定自定义区间边界,同时修正你代码里的语法问题,具体修改如下:
关键修改点
- 指定自定义分组区间:在绘制直方图时,通过
bins参数传入分组边界列表,比如bins=[0, 50, 100],就能严格按照0-50、50-100的区间生成直方图。 - 修正语法错误:原代码中
set(xlim=(0,30),ylim=(0,100)))是无效写法,需改用ax.set()或plt.xlim()设置坐标轴范围,且你需要的是0-100的范围,对应调整为xlim=(0,100)。 - 优化轴对象使用:如果函数支持传入
ax参数,建议统一基于ax操作,避免重复创建画布。 - 可选:改用推荐API:
sns.distplot在Seaborn 0.11版本后已被弃用,推荐用sns.histplot配合sns.kdeplot实现相同效果,功能更清晰。
修正后的代码(基于distplot)
import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import norm def norm_comparision_plot(data, title, figsize=(14,6), color="#099DD9", ax=None, surround=True, grid=True): # 处理轴对象,避免重复创建画布 if ax is None: fig, ax = plt.subplots(figsize=figsize) # 自定义分组区间 bins = [0, 50, 100] # 绘制直方图+正态分布拟合 sns.distplot(data, hist=True, fit=norm, color=color, kde_kws={"color": color, "lw": 3}, bins=bins, ax=ax) (mu, sigma) = norm.fit(data) # 设置X轴范围为0-100 ax.set(xlim=(0, 100)) # 添加图例和标题 ax.legend([title, f'($\\mu=$ {:.2f} and $\\sigma=$ {:.2f} )'.format(mu, sigma)], loc='best') ax.set_ylabel('') ax.set_title(title) if surround: sns.despine(trim=True, left=True, offset=10, ax=ax) if grid: ax.grid(True) # 仅在未传入ax时显示图像 if ax is None: plt.show()
推荐版本(基于histplot,替代弃用的distplot)
import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import norm def norm_comparision_plot(data, title, figsize=(14,6), color="#099DD9", ax=None, surround=True, grid=True): if ax is None: fig, ax = plt.subplots(figsize=figsize) bins = [0, 50, 100] # 绘制直方图 sns.histplot(data, bins=bins, color=color, kde=False, ax=ax) # 绘制KDE曲线 sns.kdeplot(data, color=color, lw=3, ax=ax) # 拟合并绘制正态分布曲线 (mu, sigma) = norm.fit(data) x = plt.linspace(0, 100, 100) p = norm.pdf(x, mu, sigma) ax.plot(x, p, 'r', lw=2, label=f'正态分布拟合 ($\\mu=$ {:.2f}, $\\sigma=$ {:.2f})'.format(mu, sigma)) ax.set(xlim=(0, 100)) ax.legend([title, f'($\\mu=$ {:.2f} and $\\sigma=$ {:.2f} )'.format(mu, sigma)], loc='best') ax.set_ylabel('') ax.set_title(title) if surround: sns.despine(trim=True, left=True, offset=10, ax=ax) if grid: ax.grid(True) if ax is None: plt.show()
调用函数时传入你的数据,直方图就会按照0-50、50-100的区间分组显示。
内容的提问来源于stack exchange,提问作者bian william
相关产品推荐
相关产品推荐

