与脊线图对齐标签

1 投票
1 回答
62 浏览
提问于 2025-04-14 17:28

下面的代码是为了绘制一个月度数据的山脊图(ridgeline plot)。不过,我发现月标签和密度图对不上。请看下面的代码和输出结果。有没有什么建议可以让我更新代码,使对齐更好呢?

# 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()

当前的图:

current plot

在另一个例子中,代码的对齐效果很好,但现在换了一个不同的数据集后,就对不上了。调整 hspace 也没有帮助。

other plot with nice alignment

1 个回答

0

ax.text(-15, 0.02, ...)这行代码中,把y=0.02这个参数改成y轴上平均的密度值。我觉得现在这个值太大了,导致标签被推得很高。你可能需要先删掉这一行g.set(yticks=[]),这样才能看到实际的y轴密度值,等你搞定后再把它加回来。

另外,根据@JohanC的建议(可以参考这个seaborn的山脊图示例),你可以在坐标轴中指定y=为0到1之间的值,0代表底部,1代表顶部。这样你就不需要根据数据值来设置y了。

#Place label at left (x=0) and half-way up the y axis (y=0.5)
ax.text(x=0, y=0.5, transform=ax.transAxes, s=<text string>, ...)

撰写回答