python画柱状图 python画直方图

本文介绍如何使用Python和Matplotlib库绘制包含多组数据的高级柱状图,并添加图例、横纵坐标名称及具体数值。通过示例代码演示了如何设置柱状图的宽度、位置和颜色等。

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

如题 利用python画柱状图 如何画高级柱状图 添加图例 横纵坐标名 柱状图高度 在一个柱状图上显示多个数据 画高级柱状图 添加图例 横纵坐标名 柱状图高度 画柱状对比图 【超简单教程】


代码
import matplotlib.pyplot as plt
import numpy as np

# 设置画布的大小
plt.figure(figsize=(6, 5))

# 输入统计数据
name = ('name1','name2') # 在这里设置名字
number_a = [0.81, 0.88] # 在这里设置高度
number_b = [0.68, 0.66]
number_c = [0.75, 0.83]

bar_width = 0.2  # 条形宽度
index_a = np.arange(len(name))
index_b = index_a + bar_width
index_c = index_b + bar_width
y = [number_a,number_b,number_c]
x = [index_a, index_b, index_c]


# 使用3次 bar 函数画出两组条形图
plt.bar(index_a, height=number_a, width=bar_width, color='b', label='a')
plt.bar(index_b, height=number_b, width=bar_width, color='y', label='b')
plt.bar(index_c, height=number_c, width=bar_width, color='c', label='c')

plt.legend()  # 显示图例
plt.xticks(index_a+bar_width, name)  # 将横坐标显示在每个坐标的中心位置
plt.ylim([0, 1.3])

# 给柱状图添加高度
for x_ind,y_ind in zip(x,y):
        xx1 = x_ind[0]
        xx2 = x_ind[1]
        yy1 = y_ind[0]
        yy2 = y_ind[1]
        plt.text(xx1, yy1+0.01, ('%.2f' % yy1), ha='center', va='bottom')
        plt.text(xx2, yy2+0.01, ('%.2f' % yy2), ha='center', va='bottom')


plt.xlabel('x_label__')  # 横坐标轴标题
plt.ylabel('y_label__')  # 纵坐标轴标题
plt.title('test')  # 图形标题

plt.show()

结果

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_刘文凯_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值