matplotlib之pyplot模块——为柱状图添加数据标签(bar_label())

本文介绍matplotlib 3.4.1中新增的bar_label()函数,用于为柱状图添加数据标签,演示了'center'和'edge'两种标签类型,并展示了堆积柱状图的使用技巧。通过实例展示如何增强数据可视化表达。
该文章已生成可运行项目,

当前有效matplotlib版本为:3.4.1

bar_label()概述

与其他可视化工具相比,为数据系列添加数据标签一直是matplotlib的薄弱项。bar_label()函数是matplotlib3.4.0新增API,功能是为柱状图添加数据标签。

函数的签名为matplotlib.pyplot.bar_label(container, labels=None, *, fmt='%g', label_type='edge', padding=0, **kwargs)
函数的参数为:

  • container:柱子的容器对象,通常为barbarh函数返回值。 .BarContainer对象。必备参数。
  • labels : 标签文本列表。类数组对象。可选参数。如果为None,则值为使用fmt参数格式化的柱子的数据(柱子的高度)。
  • fmt:标签的格式字符串。 字符串。默认值为'%g',即将标签值格式化为浮点数。
  • label_type :标签类型。取值范围为 {'edge', 'center'},默认值为'edge'。对于普通柱状图,该参数仅用于控制标签的位置,对于堆积柱状图,不同标签类型对应不同的标签值。
    • 'edge': 标签位于柱子的端点。显示的值为柱子的端点位置。注意!对于堆积柱状图即堆积的多个柱子的总长度。
    • 'center':标签位于柱子的中部。显示的值为柱子的长度。
  • padding : 标签与柱子之间的距离,单位为像素。浮点数。默认值为0
  • **kwargs:传递给 annotate()的其他参数。

返回值为标签的Text对象列表。

案例1:柱状图标签类型演示

import matplotlib.pyplot as plt
import numpy as np


# 构造数据
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
xlabels = ['G1', 'G2', 'G3', 'G4', 'G5']
width = 0.35

plt.subplot(211)
p1 = plt.bar(xlabels, menMeans, width, label='Men')
plt.bar_label(p1, label_type='center')
plt.title('center')
plt.subplot(212)
p2 = plt.bar(xlabels, womenMeans, width, label='Women')
plt.bar_label(p2, label_type='edge')
plt.title('edge')
plt.show()

案例2:堆积柱状图标签演示

在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np


# 构造数据
menMeans = (20, 35, 30, 35, -27)
womenMeans = (25, 32, 34, 20, -25)
xlabels = ['G1', 'G2', 'G3', 'G4', 'G5']
width = 0.35  

# 绘制堆积柱状图
p1 = plt.bar(xlabels, menMeans, width, label='Men')
p2 = plt.bar(xlabels, womenMeans, width,
            bottom=menMeans,label='Women')

plt.axhline(0, color='grey', linewidth=0.8)
plt.ylabel('Scores')
plt.title('Scores by group and gender')


plt.legend()

# 为第一段柱子添加标签
plt.bar_label(p1, label_type='center')
# 为第二段柱子添加标签
plt.bar_label(p2, label_type='center')
# 为柱子整体添加标签
plt.bar_label(p2)

plt.show()
本文章已经生成可运行项目
以下是使用matplotlib.pyplot绘制水平交错柱状图的代码,其中使用了热狗大胃王数据的前三名选手和对应的年份: ```python import matplotlib.pyplot as plt # 热狗大胃王数据 hotdog_winners = { 2019: ['Joey Chestnut', 'Darron Breeden', 'Geoffrey Esper'], 2018: ['Joey Chestnut', 'Carmen Cincotti', 'Darron Breeden'], 2017: ['Joey Chestnut', 'Carmen Cincotti', 'Matt Stonie'], 2016: ['Joey Chestnut', 'Matt Stonie', 'Carmen Cincotti'], 2015: ['Matt Stonie', 'Joey Chestnut', 'Adrian Morgan'], 2014: ['Joey Chestnut', 'Tim Janus', 'Matt Stonie'] } # 取出年份和前三名选手 years = list(hotdog_winners.keys()) winner1 = [hotdog_winners[i][0] for i in years] winner2 = [hotdog_winners[i][1] for i in years] winner3 = [hotdog_winners[i][2] for i in years] # 绘制水平交错柱状图 fig, ax = plt.subplots() bar_width = 0.25 opacity = 0.8 rects1 = ax.barh(years, winner1, bar_width, alpha=opacity, color='b', label='First Place') rects2 = ax.barh(years + bar_width, winner2, bar_width, alpha=opacity, color='g', label='Second Place') rects3 = ax.barh(years + bar_width*2, winner3, bar_width, alpha=opacity, color='r', label='Third Place') ax.set_xlabel('Winners') ax.set_ylabel('Year') ax.set_title('Hot Dog Eating Contest Winners (2004-2019)') ax.set_yticks(years + bar_width) ax.set_yticklabels(years) ax.legend() plt.tight_layout() plt.show() ``` 运行代码后,会得到以下的水平交错柱状图: ![Hot Dog Eating Contest Winners](https://i.imgur.com/7yYQCm6.png)
评论 10
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值