使用matplotlib绘制并列柱状图并在柱上方标注数值

自己查阅了资料和众多博客,记录一下,以备不时之需。
----------2021.07.30------------
补:matplotlib 3.4版本之后,已经提供了专门的在柱上方添加数值标注的api
官方给出的示例代码如下:

import matplotlib.pyplot as plt
import numpy as np


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

x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men')
rects2 = ax.bar(x + width/2, women_means, width, label='Women')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()

ax.bar_label(rects1, padding=3)  # 更加简单好用的api
ax.bar_label(rects2, padding=3)

fig.tight_layout()

plt.show()

在这里插入图片描述


----------以下为原内容--------

import numpy as np
import matplotlib.pyplot as plt


courses = ["语文", "数学", "英语", "物理", "化学", "生物"]
x_arange = np.arange(len(courses))  # [0 1 2 3 4 5],相当于x轴上的坐标序列
scores_zhangsan = [76, 98, 67, 95, 90, 82]
scores_lisi = [96, 72, 98, 69, 72, 81]

bar_width = 0.35  # 一个bar的宽度,注意x轴每两项的刻度的间距为1,注意合理设置宽度

plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  # 防止中文乱码

"""
绘制条形图,各入参的含义:
x_arange - bar_width / 2:第一个bar在x轴上的中心值,每个刻度值减一半bar宽度得到,第二个bar则是加一半bar宽度;
scores_zhangsan:bar高度,这里也就是分数值;
bar_width:bar宽度;
label:标签
"""
plt.bar(x_arange - bar_width / 2, scores_zhangsan, bar_width, label="张三")
plt.bar(x_arange + bar_width / 2, scores_lisi, bar_width, label="李四")

# 在各个bar上标注数值,使用zip()来同步遍历x_arange, scores_zhangsan, scores_lisi
for x, score_zhangsan, score_lisi in zip(x_arange, scores_zhangsan, scores_lisi):
	"""
	各入参含义:
	x - bar_width / 2:所需绘制的数值在x轴的位置;
	score_zhangsan + 1:所需绘制的数值在y轴的位置,加个1是为了在数值和bar顶部留点空隙;
	score_zhangsan:所需绘制的数值;
	ha='center':对齐方式,这里居中;
	fontsize=12:字号大小
	"""
    plt.text(x - bar_width / 2, score_zhangsan + 1, score_zhangsan, ha='center', fontsize=12)
    plt.text(x + bar_width / 2, score_lisi + 1, score_lisi, ha='center', fontsize=12)
    
plt.xlabel("考试科目")
plt.ylabel("分数")
plt.xticks(x_arange, labels=courses)  # x轴上的刻度用courses的项来绘制
plt.title("张三和李四的各科成绩对比")
plt.legend()
plt.show()

效果如下:
在这里插入图片描述
理解了这种并列柱状图的绘制原理,除了这种2个bar并列的,更多bar并列的柱状图也能类似画出。

  • 19
    点赞
  • 81
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用matplotlib绘制精美的柱并保存本地,可以按照以下步骤进行: 1. 导入matplotlib库和numpy库 ```python import matplotlib.pyplot as plt import numpy as np ``` 2. 创建数据 ```python x = np.array(['A', 'B', 'C', 'D']) y = np.array([20, 35, 30, 25]) ``` 3. 绘制 ```python fig, ax = plt.subplots() ax.bar(x, y, color='green') ax.set_title('Bar Chart') ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ``` 4. 调整样式 ```python # 设置边框颜色和粗细 for spine in ax.spines.values(): spine.set_edgecolor('#BBBBBB') spine.set_linewidth(1) # 设置x轴刻度标签旋转角度和字体大小 plt.xticks(rotation=0, fontsize=10) # 设置y轴刻度标签字体大小 plt.yticks(fontsize=10) # 设置标题字体大小 plt.title('Bar Chart', fontsize=12) # 隐藏顶部和右侧边框 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) # 添加网格线 ax.grid(axis='y', linestyle='--') ``` 5. 保存像 ```python plt.savefig('bar_chart.png', dpi=300, bbox_inches='tight') ``` 完整代码如下: ```python import matplotlib.pyplot as plt import numpy as np # 创建数据 x = np.array(['A', 'B', 'C', 'D']) y = np.array([20, 35, 30, 25]) # 绘制 fig, ax = plt.subplots() ax.bar(x, y, color='green') ax.set_title('Bar Chart') ax.set_xlabel('X Label') ax.set_ylabel('Y Label') # 调整样式 for spine in ax.spines.values(): spine.set_edgecolor('#BBBBBB') spine.set_linewidth(1) plt.xticks(rotation=0, fontsize=10) plt.yticks(fontsize=10) plt.title('Bar Chart', fontsize=12) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.grid(axis='y', linestyle='--') # 保存像 plt.savefig('bar_chart.png', dpi=300, bbox_inches='tight') ``` 运行完毕后,会在当前路径下生成一个名为 `bar_chart.png` 的像文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值