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

如何修改Seaborn多美学元素图表的图例分区标题?

修改Seaborn图表图例的分区副标题

问题描述

需要修改Seaborn relplot生成图表的图例分区副标题,默认分区标题为smoker和time,目标改为Smoker和Time of Day。此前仅能修改整个图例的标题,无法调整这些分区副标题。

原始绘图代码:

import matplotlib.pyplot as plt
import seaborn as sns
tips=sns.load_dataset('tips')
sns.relplot(
    data=tips,
    x='total_bill', y='tip', hue='smoker', style='time'
)
plt.show()

尝试过的代码(仅支持修改整体图例标题):

import matplotlib.pyplot as plt
import seaborn as sns
tips=sns.load_dataset('tips')
g = sns.relplot(
    data=tips,
    x='total_bill', y='tip', hue='smoker', style='time',
    facet_kws={'legend_out': True}
)
# 仅能设置整个图例的标题,无法修改分区副标题
g._legend.set_title('Legend')
plt.show()

解决方案

通过访问图例内部的文本元素,直接修改分区副标题内容,代码如下:

import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset('tips')
g = sns.relplot(
    data=tips,
    x='total_bill', y='tip', hue='smoker', style='time',
    facet_kws={'legend_out': True}
)

# 获取图例中的所有文本对象
legend_texts = g._legend.get_texts()

# 修改第一个分区标题(对应smoker)
legend_texts[0].set_text('Smoker')
# 修改第二个分区标题(对应time)
legend_texts[2].set_text('Time of Day')

plt.show()

关键说明

  • g._legend.get_texts()返回图例内所有文本对象的列表,其中:
    • 索引0对应hue参数指定的第一个分区(smoker)的标题
    • 索引2对应style参数指定的第二个分区(time)的标题
  • 调用set_text()方法替换文本内容,即可完成分区副标题的修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 23:15:42