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

如何将Seaborn Factorplot的Y轴标签格式化为百分比?

如何在Seaborn Factorplot中将Y轴设置为百分比格式?

当然可以实现啦!你的Y轴是0/1变量的均值,本质就是比例值,我们只需要借助Matplotlib的刻度格式化工具,就能轻松把这些小数转成百分比显示。

下面是修改后的完整代码,我帮你加入了百分比格式化的部分,还顺手调整了一些细节:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from matplotlib.ticker import PercentFormatter  # 导入百分比格式化工具

plt.figure(figsize=(10, 7))
# 注意:factorplot在Seaborn新版本中已更名为catplot,推荐使用catplot
g = sns.factorplot(
    x="groups", 
    y="has_invoice", 
    hue='kind', 
    x_estimator=np.mean, 
    data=df[df['app'] != 'other, other, web'], 
    order=['< 2', '2-4', '4-6', '6-8', '8-10', '10-12', '12-14', '14-16', '>16'], 
    size=7, 
    aspect=1
)
# 设置Y轴为百分比格式
g.axes[0,0].yaxis.set_major_formatter(PercentFormatter(1.0))

plt.xlabel('# of items')  # 可根据实际场景补充完整标签
plt.title('Invoice Rate by Group and Kind')  # 建议补充明确标题
plt.ylabel('Invoice Rate')
plt.show()

关键说明:

  • PercentFormatter(1.0)里的1.0是告诉工具:当前Y轴的最大值对应100%,因为你的均值是0到1之间的比例值,这样就能把0.5转成50%、0.8转成80%
  • 如果你的Seaborn版本较新,建议把factorplot换成catplot,用法几乎一致,是官方推荐的新接口
  • 我补全了一些标签和标题的占位,你可以根据实际需求修改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:25:12