如何让Seaborn绘制的多组山脊图更紧凑、重叠度更高、高度显示更清晰
调整方案
- 增大子图负间距:将
subplots_adjust的hspace参数从-0.1调整为-0.4~-0.6之间,数值绝对值越大重叠度越高,可根据你的分组数量微调。 - 统一KDE高度基准:给
sns.kdeplot添加common_norm=True参数,让所有组的KDE高度按统一标准缩放,避免各组曲线高度差异过大难以辨识;同时可添加bw_adjust参数调整曲线平滑度,避免过度平滑丢失细节。 - 降低填充透明度:将填充的
alpha从1调整为0.7~0.8,保证上层曲线不会完全遮挡下层的轮廓。 - 优化标签显示:调整标签的垂直位置,同时添加白色半透明背景框,避免标签被上层曲线遮挡。
- 可选调整:给KDE添加
clip参数,将曲线范围限制在你的数据实际取值区间内,减少无效的长尾占比,让核心数据区域的显示更紧凑。
修改后参考代码
import seaborn as sns import matplotlib.pyplot as plt sns.set_theme(style="white", rc={"axes.facecolor":(0,0,0,0), 'axes.linewidth':2}) palette = sns.color_palette("Set2", 12) def label(x, color, label): ax = plt.gca() # 调整标签位置,添加半透明背景避免被遮挡 ax.text(0, .1, label, color='black', fontsize=12, ha="left", va="center", transform=ax.transAxes, bbox=dict(facecolor='white', alpha=0.8, edgecolor='none', pad=0)) g = sns.FacetGrid(df_comp, palette=palette, row="temperature", hue="temperature", aspect=9, height=1.2) # 调整KDE参数,统一高度基准、设置透明度 g.map_dataframe(sns.kdeplot, x="Rg", fill=True, alpha=0.7, common_norm=True, bw_adjust=0.8) g.map_dataframe(sns.kdeplot, x="Rg", color='black', lw=1, common_norm=True, bw_adjust=0.8) # 增大负间距提升重叠度 g.fig.subplots_adjust(hspace=-.5) g.map(label, "temperature") g.set_titles("") g.set(yticks=[], xlabel="Rg值") g.despine(left=True) plt.show()
内容的提问来源于stack exchange,提问作者bad_chemist
相关产品推荐
相关产品推荐

