如何调整Python代码使月份标签与山脊线密度图对齐?
山脊线图月份标签与密度图对齐问题修复建议
问题描述
我编写了Python代码绘制月度数据的山脊线图,目前无法将月份标签与对应的密度图对齐。此前使用其他数据集时代码可正常对齐,但换用当前数据集后对齐失效,调整hspace参数也无济于事。
原代码
# Set color pallete pal = sns.color_palette(palette='coolwarm', n_colors=12) # Apply sns.FacetGrid class, with the 'hue' argument to represented colors by 'palette' g = sns.FacetGrid(wind, row='month', hue='mean_month', aspect=15, height=0.75, palette=pal, xlim=(0,100)) # Add the densities kdeplots for each month g.map(sns.kdeplot, 'Normalized', bw_adjust=1, clip=(0,100), fill=True, alpha=1, linewidth=1.5) # Add a horizontal line for each plot g.map(plt.axhline, y=0, lw=2, clip_on=False) # Loop over the FacetGrid figure axes (g.axes.flat) and add the month as text with the right color for i, ax in enumerate(g.axes.flat): ax.text(-15, 0.02, month_dict[i+1], fontweight='bold', fontsize=14, color=ax.lines[-1].get_color()) # Use matplotlib.Figure.subplots_adjust() function for subplots to overlap g.figure.subplots_adjust(hspace=-0.1) # Remove axes titles, yticks, etc. and add labels g.set_titles("") g.set(yticks=[]) g.set(ylabel=None) g.despine(bottom=True, left=True) plt.setp(ax.get_xticklabels(), fontsize=15, fontweight='bold') plt.xlabel('Wind output [%]', fontweight='bold', fontsize=15) g.figure.suptitle('Dutch Offshore wind per month (2021-2022)', ha='right', fontsize=20, fontweight=20) plt.show()
当前效果与理想效果
- 当前未对齐图表:

- 理想对齐效果:

修复方案
1. 改用轴坐标固定标签位置
问题核心是用了固定的y轴数值(0.02)放置标签,但不同月份的密度曲线y轴范围差异大,导致标签相对位置偏移。改用轴坐标(相对于子图的比例位置)可以确保标签始终和对应子图垂直居中:
替换标签循环部分代码:
for i, ax in enumerate(g.axes.flat): # 使用轴坐标(0=左,1=右;0=底,1=顶),固定在子图左侧垂直居中位置 ax.text(-0.08, 0.5, month_dict[i+1], fontweight='bold', fontsize=14, color=ax.lines[-1].get_color(), ha='center', va='center', transform=ax.transAxes)
2. 确保月份列有序
检查wind数据中month列的排序是否为1-12月,若为字符串或乱序,FacetGrid子图顺序会混乱,导致标签对应错误。添加以下代码强制排序:
import pandas as pd # 确保month列按1-12顺序排列 wind['month'] = pd.Categorical(wind['month'], categories=range(1,13), ordered=True)
3. 统一密度图归一化方式
绘制kdeplot时添加common_norm=False,避免不同子图的密度归一化规则不同导致y轴范围差异过大:
g.map(sns.kdeplot, 'Normalized', bw_adjust=1, clip=(0,100), fill=True, alpha=1, linewidth=1.5, common_norm=False)
4. 修复其他小问题
- 原代码仅修改了最后一个子图的x轴标签大小,改为
g.get_xticklabels()统一修改所有子图:plt.setp(g.get_xticklabels(), fontsize=15, fontweight='bold') - 原代码
fontweight=20参数无效,改为fontweight='bold'或数值700:g.figure.suptitle('Dutch Offshore wind per month (2021-2022)', ha='right', fontsize=20, fontweight='bold')
修改后的完整代码
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd # 确保month列按1-12顺序排列 wind['month'] = pd.Categorical(wind['month'], categories=range(1,13), ordered=True) # Set color pallete pal = sns.color_palette(palette='coolwarm', n_colors=12) # Apply sns.FacetGrid class, with the 'hue' argument to represented colors by 'palette' g = sns.FacetGrid(wind, row='month', hue='mean_month', aspect=15, height=0.75, palette=pal, xlim=(0,100)) # Add the densities kdeplots for each month,关闭统一归一化 g.map(sns.kdeplot, 'Normalized', bw_adjust=1, clip=(0,100), fill=True, alpha=1, linewidth=1.5, common_norm=False) # Add a horizontal line for each plot g.map(plt.axhline, y=0, lw=2, clip_on=False) # Loop over the FacetGrid figure axes (g.axes.flat) and add the month as text with the right color for i, ax in enumerate(g.axes.flat): # 使用轴坐标固定标签位置,垂直居中 ax.text(-0.08, 0.5, month_dict[i+1], fontweight='bold', fontsize=14, color=ax.lines[-1].get_color(), ha='center', va='center', transform=ax.transAxes) # Use matplotlib.Figure.subplots_adjust() function for subplots to overlap g.figure.subplots_adjust(hspace=-0.1) # Remove axes titles, yticks, etc. and add labels g.set_titles("") g.set(yticks=[]) g.set(ylabel=None) g.despine(bottom=True, left=True) plt.setp(g.get_xticklabels(), fontsize=15, fontweight='bold') plt.xlabel('Wind output [%]', fontweight='bold', fontsize=15) g.figure.suptitle('Dutch Offshore wind per month (2021-2022)', ha='right', fontsize=20, fontweight='bold') plt.show()
内容的提问来源于stack exchange,提问作者Marky
相关产品推荐
相关产品推荐

