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
相关产品推荐
相关产品推荐

