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

如何在seaborn relplot生成的多张子图上叠加pyplot视觉元素

问题原因

直接调用plt.axvline、plt.axvspan这类pyplot全局接口时,操作仅会作用于当前处于激活状态的子图。seaborn的relplot生成多张子图后,默认激活的是最后完成渲染的子图,因此你的高亮元素只会出现在最后一张图表上。

解决方案

把高亮逻辑放到遍历所有子图的循环中,给每个子图对象单独调用对应方法添加元素即可,修改后的完整代码如下:

import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

# relplot 绘图逻辑
sns.set_theme(style="whitegrid")
graph2 = sns.relplot(
    x="variable", y="value", col='Instance_x', data=df_final,
    kind='line', col_wrap=2, hue='Instance_x',
    facet_kws={'sharey':False}, ci=None
)
graph2.fig.subplots_adjust(top=0.9)
graph2.fig.suptitle('Annual Savings per Instance (HA Scenario, AWS)', fontdict={ 'fontsize': 14, 'fontweight':'bold'})
graph2.set_axis_labels('Average Annual Utilization (%)','Average Annual Savings per Virtual machine ($)', fontsize = 14)

# 遍历所有子图做配置
for ax in graph2.axes:
    # 原有y轴配置
    ax.yaxis.set_major_locator(ticker.FixedLocator(ax.get_yticks().tolist()))
    ax.set_yticklabels(ax.get_yticks(), size = 13)
    ax.yaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
    # 新增:给每个子图添加高亮区域和竖线
    ax.axvline(25, color='grey', lw=1.3)
    ax.axvline(50, color='grey', lw=1.3)
    ax.axvspan(25, 50, alpha=0.2, facecolor='lightgrey')

# 单独配置前两个子图的x轴
graph2.axes[0].xaxis.set_major_locator(ticker.FixedLocator(graph2.axes[0].get_xticks().tolist()))
graph2.axes[1].xaxis.set_major_locator(ticker.FixedLocator(graph2.axes[1].get_xticks().tolist()))
graph2.axes[0].xaxis.set_major_formatter(ticker.PercentFormatter())
graph2.axes[1].xaxis.set_major_formatter(ticker.PercentFormatter())
graph2.axes[0].invert_xaxis()

plt.show()

上述修改已经保证所有子图都会出现相同的高亮元素,已经做了x轴反转的子图也会自动适配高亮区域的坐标规则,不需要额外调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 03:09:04