python Matplotlib 系列教程(三)——绘制直方图和条形图

条形图与直方图的区别:

首先,条形图是用条形的长度表示各类别频数的多少,其宽度(表示类别)则是固定的;

直方图是用面积表示各组频数的多少,矩形的高度表示每一组的频数或频率,宽度则表示各组的组距,因此其高度与宽度均有意义。

其次,由于分组数据具有连续性,直方图的各矩形通常是连续排列,而条形图则是分开排列。

最后,条形图主要用于展示分类数据,而直方图则主要用于展示数据型数据

首先来看一个条形图的例子:

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf", size=14)  

plt.bar([1, 3, 5, 7, 9], [5, 4, 8, 12, 7], label='graph 1')

plt.bar([2, 4, 6, 8, 10], [4, 6, 8, 13, 15], label='graph 2')

# params

# x: 条形图x轴
# y:条形图的高度
# width:条形图的宽度 默认是0.8
# bottom:条形底部的y坐标值 默认是0
# align:center / edge 条形图是否以x轴坐标为中心点或者是以x轴坐标为边缘

plt.legend()

plt.xlabel('number')
plt.ylabel('value')

plt.title(u'测试例子——条形图', FontProperties=font)

plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

这里写图片描述

【注】如果我们没有明确选择一种颜色,虽然我们做了多个图,但是所有的图都会看起来一样,即颜色是一样。

下面我们看一个直方图的例子:

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf", size=14)  

salary = [2500, 3300, 2700, 5600, 6700, 5400, 3100, 3500, 7600, 7800, 
          8700, 9800, 10400]

group = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000]


plt.hist(salary, group, histtype='bar', rwidth=0.8)

plt.legend()

plt.xlabel('salary-group')
plt.ylabel('salary')

plt.title(u'测试例子——直方图', FontProperties=font)

plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

这里写图片描述

这是一个简单的工资分布情况图,可以很直观的得到例如在2000-3000水平的人数有2人。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值