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

如何为Matplotlib柱状图添加数值标签并将缺失值替换为0

解决柱状图数值显示与缺失值替换问题

没问题,我来帮你搞定这两个需求——把数据里的缺失值换成0,同时在每个柱状图的柱子上显示高度数值。咱们一步步来修改代码:

第一步:处理数据中的缺失值

你原数据里的"NAN"是字符串类型,pandas没法直接识别为缺失值,所以得先把这些字符串转成真正的NaN,再用0填充。另外数值列有浮点和字符串混合的情况,统一转成整数会让显示更整洁:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 初始化数据集
data = {'Hospital_name':['Jootrh Hospital', 'Jootrh Hospital', 'Embu Hospital', 'Embu Hospital','Bungoma Hospital', 'Bungoma Hospital', 'Keru Hospital', 'Keru Hospital'], 
        'periodname':["18-Jul", "18-Aug", "18-Jul", "18-Aug","18-Jul", "18-Aug", "18-Jul", "18-Aug"], 
        'normal deliveries':[452, 458, "NAN", 45,498, 466, "NAN", 450], 
        'caesarian sections':[67.0, 99.0, 13.0, 13.0,60.0, 19.0, 73.0, "NAN"], 
        'breach delivery':[10.0, "NAN", 13.0, 137.0,100.0, "NAN", "NAN" ,197.0], 
        'assisted vd':["NAN", "NAN", 1.0, 37.0,1.0, "NAN", 1.0, 37.0]}

# 创建DataFrame并处理缺失值
df = pd.DataFrame(data)
# 将字符串"NAN"替换为pandas可识别的缺失值,再填充为0
df = df.replace("NAN", np.nan).fillna(0)
# 把数值列转为整数(可选,让显示更清爽)
numeric_cols = ['normal deliveries', 'caesarian sections', 'breach delivery', 'assisted vd']
df[numeric_cols] = df[numeric_cols].astype(int)

第二步:修改绘图代码,添加柱子高度数值

在原有的绘图循环里,我们需要遍历每个柱子(matplotlib里叫patch),获取它的高度和位置,然后把数值文本添加到柱子上方:

# 设置索引并分组
df.set_index('periodname', inplace=True)
grouped = df.groupby('Hospital_name')
ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols,figsize=(20,50), constrained_layout=True)

for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
    # 绘制当前医院的柱状图
    ax = grouped.get_group(key).plot(kind='bar', ax=ax, title=key)
    ax.legend()
    
    # 遍历每个柱子,添加数值标签
    for patch in ax.patches:
        height = patch.get_height()
        # 计算文本的x坐标(柱子中心)
        x_pos = patch.get_x() + patch.get_width() / 2
        # 在柱子上方居中位置添加数值
        ax.text(x_pos, height, f'{int(height)}', ha='center', va='bottom', fontsize=10)

plt.show()

代码说明

  • 缺失值处理:replace("NAN", np.nan)把字符串缺失值转为pandas标准缺失值,fillna(0)将所有缺失值替换为0;转整数是为了避免显示.0这样的小数。
  • 数值标签:通过ax.patches获取所有柱子对象,用get_height()拿到高度,计算中心位置后用ax.text()把数值贴上去,ha='center'保证水平居中,va='bottom'让数值贴在柱子顶部。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:28:20