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

如何调整Seaborn catplot图例的字体大小?

调整Seaborn Catplot图例字体大小的方法

要增大catplot的图例字体大小,你可以利用catplot返回的FacetGrid对象直接操作图例,以下是两种简单有效的方法:

方法1:直接设置图例字体大小

在现有代码中添加一行,通过FacetGrid的legend属性调用set_fontsize():

sns.set_theme(style="whitegrid")
res = sns.catplot(data=sameday_trips,kind="bar",x="SameDay",y="Trip Completed",hue="Pickup point",
            palette="dark", alpha=.6, height=6)
res.despine(left=True)
res.set_xlabels("SameDay Trip?",fontsize=20)
res.set_ylabels("Trips Completed",fontsize=20)
res.set_xticklabels(fontsize=20)
res.set_yticklabels(fontsize=20)

# 添加这行调整图例字体大小
res.legend.set_fontsize(20)

plt.show()

方法2:用plt.setp批量设置图例文本

如果需要更精细的控制,也可以用plt.setp来设置图例中所有文本的字体大小:

sns.set_theme(style="whitegrid")
res = sns.catplot(data=sameday_trips,kind="bar",x="SameDay",y="Trip Completed",hue="Pickup point",
            palette="dark", alpha=.6, height=6)
res.despine(left=True)
res.set_xlabels("SameDay Trip?",fontsize=20)
res.set_ylabels("Trips Completed",fontsize=20)
res.set_xticklabels(fontsize=20)
res.set_yticklabels(fontsize=20)

# 添加这行调整图例字体大小
plt.setp(res.legend.get_texts(), fontsize=20)

plt.show()

额外提示

你原代码中的plt.figure(figsize=[20,10])对catplot无效,因为catplot会自行创建新的画布。如果需要调整catplot的整体尺寸,可以直接在catplot参数里设置height和aspect(比如height=8, aspect=2)来控制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 12:45:33