如何调整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
相关产品推荐
相关产品推荐

