matplotlib——直方图
实验目的
了解hist函数的每个参数的含义
掌握使用matplotlib画直方图的方法
实验原理
直方图
函数原型:matplotlib.pyplot.hist(x, bins=None, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, hold=None, data=None, **kwargs)
- x : (n,) array or sequence of (n,) arrays(指定每个bin(箱子)分布的数据,对应x轴)
- bins : integer or array_like, optional,这个参数指定bin(箱子)的个数,也就是总共有几条条状图,默认为10;
- range : tuple or None, optional(设置显示的范围,范围之外的将被舍弃)
- normed :boolean,用于对数据进行正则化,当该参数的值为 Ture 时,图中显示的数据将会是正态正则化之后的结果
- weights : (n, ) array_like or None, optional(?)
- cumulative : boolean, optional就是每一列都把之前的加起来
- bottom : array_like, scalar, or None 条形图y坐标即每一个块的底部高度
- histtype : {‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}, optional(选择展示bar的形状,默认为bar)
- align : {‘left’, ‘mid’, ‘right’}, optional(对齐方式)
- orientation : {‘horizontal’, ‘vertical’}, optional指的方向,分为水平与垂直两个方向。
- log : boolean, optional(log刻度)
- color : color or array_like of colors or None, optional(颜色设置)
- label : string or None, optional给图加刻度标签
- stacked : boolean, optional 作用就是当多个输入的时候,要不要把它们叠加起来
实验环境
Python 3.6.1
PyCharm
实验内容
使用matplotlib.pyplot中的hist函数绘制直方图。
实验步骤
1.打开Pycharm,选择Create New Project,
创建名为matplotlib6的项目。
2.打开matplotlib6项目,右键选择New=>Python File,
创建名为hist的Python文件。
3.打开hist.py文件,编写代码,用于绘制直方图。
导入包matplotlib的pyplot模块,用别名plt表示,导入包numpy,并用别名np表示。
- import numpy as np
- import matplotlib.pyplot as plt
4.创建一张图
- fig=plt.figure(1)
5.创建一个子图
- ax1=fig.add_subplot(111)
6.使用numpy包中的array函数绘制绘图所需的数据。
- np.random.seed(19680801)
- mu, sigma = 100, 15
- x = mu + sigma * np.random.randn(10000)
7.通过hist函数来绘制直方图的主体,并传入对数据进行正则化normed=1,条数bins=50,颜色facecolor=‘g’,透明度alpha=0.75等参数。
- n,bins,patches=ax1.hist(x,bins=50,normed=1,facecolor=‘g’,alpha=0.75)
8.添加一条最完美的mu=100,sigma=15正态曲线。
- y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
- np.exp(-0.5 * (1 / sigma * (bins - mu))**2))
- ax1.plot(bins, y, ‘–’)
9.绘制x,y坐标轴标签、直方图内容标签,以及图形标题。
- ax1.set_xlabel(‘Smarts’)
- ax1.set_ylabel(‘Probability’)
- ax1.set_title(‘Histogram of IQ’)
- plt.text(60,0.025,r’ μ = 100 , σ = 15 \mu=100,\ \sigma=15 μ=100, σ=15’)
10.使用axis函数调整坐标范围,使用grid函数添加网格。
- ax1.axis([40,160,0,0.03])
- ax1.grid(True)
- plt.show()
11.完整代码:
- import numpy as np
- import matplotlib.pyplot as plt
- fig=plt.figure(1)
- ax1=fig.add_subplot(111)
- np.random.seed(19680801)
- mu, sigma = 100, 15
- x = mu + sigma * np.random.randn(10000)
- n,bins,patches=ax1.hist(x,bins=50,normed=1,facecolor=‘g’,alpha=0.75)
- y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
- np.exp(-0.5 * (1 / sigma * (bins - mu))**2))
- ax1.plot(bins, y, ‘–’)
- ax1.set_xlabel(‘Smarts’)
- ax1.set_ylabel(‘Probability’)
- ax1.set_title(‘Histogram of IQ’)
- plt.text(60,0.025,r’ μ = 100 , σ = 15 \mu=100,\ \sigma=15 μ=100, σ=15’)
- ax1.axis([40,160,0,0.03])
- ax1.grid(True)
- plt.show()
12.代码编写完毕,在hist.py文件内,点击右键=》Run ‘hist’,执行hist.py文件。
13.在屏幕上打印出下面的图。