使用Matplotlib制作“条形图”:pyplot.bar(x, height, width, bottom, tick_label, label, **kwargs)

本文将介绍绘制条形图plt.bar()的方法,主要内容:

(1)绘制条形图,纵向,横向两种标示方式;
(2)一图绘制两组数据(和其他图不同的是,条形图绘制两组数据还涉及到bar宽度的计算)
(3)显示误差柱
(4)单条柱的颜色渲染


1. 纵向图形

plt.bar(x, height, width, bottom, **kwargs)
  • 参数 x,height,width,bottom,align:确定了柱体的位置和宽度

(1)参数(x, height)定义在什么位置上,多高的bar(注意X的值和X轴区别)
(2)参数 width 定义bar的宽度
(3)参数 bottom 定义bar的其实高度(常用于用堆叠的方式展示两组数据)

import matplotlib.pyplot as plt
X = [0.3, 1.7, 4, 6, 7]
height = [5, 20, 15, 25, 10]

plt.bar(X, height, width=0.6, bottom=[10, 0, 5, 0, 5] )
plt.show()

在这里插入图片描述
注意:这个图中,X轴上X的值是没有标示出来的!!

  • tick_label 参数:在X轴上标示X的“值”
import matplotlib.pyplot as plt

labels = ['0.3', '1.7', '4.0','6.0','7.0']

X = [0.3, 1.7, 4, 6, 7]
height = [5, 20, 15, 25, 10]
height2 = [10, 0, 5, 0, 5]

plt.bar(X, height, width=0.6, bottom=height2,tick_label=labels )
plt.bar(X, height2, width=0.6)
plt.show()

在这里插入图片描述
注意:这个图中,两组数据没有标示出来区别!!

  • 两组数据对比的条形图+label参数+plt.legend():需要控制好每组柱体的位置和大小
iimport matplotlib.pyplot as plt

drinks = ["cappuccino", "latte", "chai", "americano", "mocha", "espresso"]
sales1 =  [91, 76, 56, 66, 52, 27]
sales2 = [65, 82, 36, 68, 38, 40]

# 如果两句plt.bar()都写tick_label参数,则后面一句会覆盖前面一句,即展示在“b”柱下
x=np.arange(6)
plt.bar(x, sales1,  width=0.35, label='a',tick_label=drinks)
plt.bar(x + 0.35, sales2, width=0.35, label='b')

plt.legend()
plt.show()

在这里插入图片描述

  • bar颜色和填充参数

(1)facecolor(或fc) 关键字参数可以设置柱体颜色
(2)通过 color 关键字参数 可以一次性设置多个颜色
(3)hatch 关键字可用来设置填充样式,可取值为: / , \ , | , - , + , x , o , O , . , *

  • bar 描边参数:

(1)edgecolor 或 ec
(2)linestyle 或 ls
(3)linewidth 或 lw

  • 误差柱:plt.bar()中其他参数

(1)参数yerr:误差值
(2)参数capsize:展示出来的误差I图形中上下两横线的长度

from matplotlib import pyplot as plt

drinks = ["cappuccino", "latte", "chai", "americano", "mocha", "espresso"]
ounces_of_milk = [6, 9, 4, 0, 9, 0]
error = [0.6, 0.9, 0.4, 0, 0.9, 0]

plt.bar(range(len(drinks)), ounces_of_milk, yerr=error, capsize=5)
plt.show()

在这里插入图片描述

2. 横向图形

plt.barh(bottom, width, height, left=None, **kwargs)

需要注意的是:
(1)参数(bottom, width)实际上就是(x,height)只是将XY轴互换
(2)参数 height 定义bar的“厚度”即宽度

  • 12
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值