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

Python自定义函数:图表标题居中失败及柱状图显示问题求助

解决柱状图的两个问题:标签居中和显示百分比

以下是修改后的代码,直接解决你提到的两个问题:

import matplotlib.pyplot as plt
import seaborn as sns

def plot_percentage(df, col, target):
    x, y = col, target
    temp_df = df.groupby(x)[y].value_counts(normalize=True)
    temp_df = temp_df.mul(100).rename('percent').reset_index()
    # 替换硬编码列名,用参数y增强函数通用性
    temp_df = temp_df[temp_df[y] != 0]
    order_list = list(df[col].unique())
    order_list.sort()
    sns.set(font_scale=1.5)
    g = sns.catplot(x=x, y='percent', hue=x, kind='bar', data=temp_df, height=8, aspect=2, order=order_list, legend_out=False)
    g.ax.set_ylim(0, 100)
    
    # 问题1:设置x轴标签居中对齐
    g.ax.set_xticklabels(g.ax.get_xticklabels(), ha='center', fontsize=20)
    
    # 问题2:在每个柱状图上方添加百分比数值
    for p in g.ax.patches:
        height = p.get_height()
        # 在柱子顶部偏移1个单位的位置显示格式化百分比,避免重叠
        g.ax.text(p.get_x() + p.get_width()/2., height + 1,
                  f'{height:.1f}%',
                  ha='center', va='bottom', fontsize=16)
    
    plt.title(f'{col.title()} By Percent {target.title()}', 
              fontdict={'fontsize': 30})
    plt.xlabel(f'{col.title()}', fontdict={'fontsize': 20})
    plt.ylabel(f'{target.title()} Percentage', fontdict={'fontsize': 20})
    return g

修改说明:

  • x轴标签居中:通过g.ax.set_xticklabels()设置ha='center'(水平对齐为居中),同时统一标签字体大小,保证样式一致性。
  • 显示柱状图百分比:遍历所有柱子元素(g.ax.patches),获取每个柱子的高度和位置,在柱子顶部添加格式化的百分比文本,通过ha='center'确保文本居中,height +1的偏移量避免文本与柱子重叠。
  • 额外优化:将原代码中硬编码的HeartDisease替换为参数y,让函数可以适配不同的目标列,提升通用性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 06:55:15