Python Matplotlib 柱状图加数值

本文介绍如何使用Python的Matplotlib库在柱状图上添加数值标签,通过两种方法实现:使用annotate和text函数。示例代码展示了如何创建带有数值标签的双组柱状图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python Matplotlib 柱状图加数值

  • 柱状图加数值也是一项常规操作,这里采用的函数是text,主要获取加入text的位置与数值即可,因此,详细代码如下:
  • 这里写了auto_label与auto_text,两个都可以用,本人更喜欢用auto_text
import matplotlib
import matplotlib.pyplot as plt
import numpy as np


def auto_label(rects):
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height), # put the detail data
                    xy=(rect.get_x() + rect.get_width() / 2, height), # get the center location.
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')


def auto_text(rects):
    for rect in rects:
        ax.text(rect.get_x(), rect.get_height(), rect.get_height(), ha='left', va='bottom')


labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]

index = np.arange(len(labels))
width = 0.2

fig, ax = plt.subplots()
rect1 = ax.bar(index - width / 2, men_means, color ='lightcoral', width=width, label ='Men')
rect2 = ax.bar(index + width / 2, women_means, color ='springgreen', width=width, label ='Women')

ax.set_title('Scores by gender')
ax.set_xticks(ticks=index)
ax.set_xticklabels(labels)
ax.set_ylabel('Scores')

ax.set_ylim(0, 50)
# auto_label(rect1)
# auto_label(rect2)
auto_text(rect1)
auto_text(rect2)

ax.legend(loc='upper right', frameon=False)
fig.tight_layout()
plt.savefig('2.tif', dpi=300)
plt.show()

在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值