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

如何为多DataFrame子图的柱状图添加柱形数值标签?

为子图柱状图的柱形添加数值标签

我已经用四个DataFrame绘制了子图柱状图,现在需要给每个柱形顶部添加对应的数值标签,该怎么实现?

我的代码如下:

import pandas as pd
import matplotlib.pyplot as plt

# 创建四个DataFrame
data1 = {'column1': [10.123456],
        'column2': [2.345678]}
data2 = {'column1': [50.123456],
        'column2': [5.345678]}
data3 = {'column1': [100.123456],
        'column2': [10.345678]}
data4 = {'column1': [150.123456],
        'column2': [12.345678]}

df1 = pd.DataFrame(data1, index=[100])
df2 = pd.DataFrame(data2, index=[1000])
df3 = pd.DataFrame(data3, index=[10000])
df4 = pd.DataFrame(data4, index=[100000])

# 创建子图
fig, axes = plt.subplots(figsize=(15,8), nrows=1, ncols=4);

# 绘制每个子图的柱状图
df1[["column1", "column2"]].plot(ax=axes[0], rot=0, kind='bar', width=0.4, edgecolor='white', linewidth=5, 
                                      color=["blue", "green"], legend=None, fontsize=12);
df2[["column1", "column2"]].plot(ax=axes[1], rot=0, kind='bar', width=0.4, edgecolor='white', linewidth=5, 
                                      color=["blue", "green"], legend=None, fontsize=12);
df3[["column1", "column2"]].plot(ax=axes[2], rot=0, kind='bar', width=0.4, edgecolor='white', linewidth=5, 
                                      color=["blue", "green"], legend=None, fontsize=12);
df4[["column1", "column2"]].plot(ax=axes[3], rot=0, kind='bar', width=0.4, edgecolor='white', linewidth=5, 
                                      color=["blue", "green"], legend=None, fontsize=12);

当前柱状图效果


实现方法

可以通过遍历每个子图的柱形元素,调用ax.text()在柱形顶部添加数值标签。为了避免重复代码,建议封装一个通用函数来处理所有子图。

修改后的完整代码

import pandas as pd
import matplotlib.pyplot as plt

# 创建四个DataFrame
data1 = {'column1': [10.123456],
        'column2': [2.345678]}
data2 = {'column1': [50.123456],
        'column2': [5.345678]}
data3 = {'column1': [100.123456],
        'column2': [10.345678]}
data4 = {'column1': [150.123456],
        'column2': [12.345678]}

df1 = pd.DataFrame(data1, index=[100])
df2 = pd.DataFrame(data2, index=[1000])
df3 = pd.DataFrame(data3, index=[10000])
df4 = pd.DataFrame(data4, index=[100000])

# 创建子图
fig, axes = plt.subplots(figsize=(15,8), nrows=1, ncols=4);

# 绘制每个子图的柱状图
df1[["column1", "column2"]].plot(ax=axes[0], rot=0, kind='bar', width=0.4, edgecolor='white', linewidth=5, 
                                      color=["blue", "green"], legend=None, fontsize=12);
df2[["column1", "column2"]].plot(ax=axes[1], rot=0, kind='bar', width=0.4, edgecolor='white', linewidth=5, 
                                      color=["blue", "green"], legend=None, fontsize=12);
df3[["column1", "column2"]].plot(ax=axes[2], rot=0, kind='bar', width=0.4, edgecolor='white', linewidth=5, 
                                      color=["blue", "green"], legend=None, fontsize=12);
df4[["column1", "column2"]].plot(ax=axes[3], rot=0, kind='bar', width=0.4, edgecolor='white', linewidth=5, 
                                      color=["blue", "green"], legend=None, fontsize=12);

# 定义添加数值标签的函数
def add_value_labels(ax, fmt='%.2f'):
    # 遍历每个柱形
    for bar in ax.patches:
        # 获取柱形的高度(数值)
        height = bar.get_height()
        # 在柱形顶部居中位置添加文本标签
        ax.text(bar.get_x() + bar.get_width()/2.,  # x坐标:柱形中心
                height,  # y坐标:柱形顶部
                fmt % height,  # 格式化后的数值
                ha='center', va='bottom', fontsize=10)  # 对齐方式和字体大小

# 给每个子图添加数值标签
for ax in axes:
    add_value_labels(ax)

plt.tight_layout()
plt.show()

关键说明

  • add_value_labels函数:遍历子图中的所有柱形(ax.patches),获取每个柱形的高度,然后在柱形顶部居中位置添加格式化后的数值标签。
  • 格式化参数fmt='%.2f'可按需调整,比如要显示4位小数用'%.4f',显示整数用'%d'。
  • ha='center'和va='bottom'确保标签在柱形顶部居中对齐,避免偏移。
  • 调用plt.tight_layout()可自动调整子图间距,防止标签被截断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:52:30