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

如何绘制高度为百分比、标注原始数值的柱状图?

解决方案:调整柱状图高度为百分比并显示原始数值标注

核心思路

先将原始数值转换为以40为基准的百分比(公式:百分比 = (原始值 / 40) * 100),用百分比作为柱状图的高度,再将原始数值作为标注添加到柱子顶部。

完整代码示例

假设你的DataFrame包含类别列和原始数值列,以下是基于Matplotlib的实现:

import pandas as pd
import matplotlib.pyplot as plt

# 模拟你的数据(替换为实际DataFrame)
df = pd.DataFrame({
    '分组': ['组1', '组2', '组3', '组4', '组5', '组6', '组7'],
    '原始数值': [40, 40, 40, 40, 40, 33, 17]
})

# 计算百分比(基准值为40,对应100%)
df['百分比'] = (df['原始数值'] / 40) * 100

# 绘制柱状图
fig, ax = plt.subplots(figsize=(10, 6))
bars = ax.bar(df['分组'], df['百分比'], color='#1f77b4')

# 添加原始数值标注到柱子顶部
for bar, raw_val in zip(bars, df['原始数值']):
    bar_height = bar.get_height()
    # 调整标注位置,避免与柱子顶部重叠
    ax.text(
        bar.get_x() + bar.get_width()/2,  # 水平居中
        bar_height + 1,  # 垂直方向略高于柱子
        str(raw_val),
        ha='center', va='bottom', fontsize=10
    )

# 美化图表
ax.set_ylabel('百分比 (%)')
ax.set_title('柱状图:高度对应百分比,标注为原始数值')
ax.set_ylim(0, 105)  # 预留顶部空间放标注
plt.xticks(rotation=0)
plt.tight_layout()
plt.show()

关键说明

  • 百分比转换:通过(原始值/40)*100确保40对应100%,17对应42.5%,完全匹配需求
  • 标注添加:使用ax.text()遍历每个柱子,将原始数值精准定位在柱子上方,ha='center'保证水平居中,va='bottom'避免标注被柱子遮挡
  • 适配其他库:如果使用Seaborn,核心逻辑一致——先计算百分比列,用百分比绘制柱状图,再手动添加原始数值标注

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 23:32:34