您的位置:首页 > 编程语言 > Python开发

python—matplotlib数据可视化实例注解系列-----之柱状图

2017-09-11 09:57 1181 查看
本文代码源自官方实例,部分进行了修改和注解方便学习和查询。

Matplotlib.pyplot中hist()的参数:
n, bins, patches = plt.hist(arr, bins=10, normed=0,facecolor='black', edgecolor='black',alpha=1,histtype='bar')

hist的参数非常多,但常用的就这六个,只有第一个是必须的,后面四个可选
 
arr: 需要计算直方图的一维数组
bins: 直方图的柱数,可选项,默认为10
normed: 是否将得到的直方图向量归一化。默认为0
facecolor: 直方图颜色
edgecolor: 直方图边框颜色
alpha: 透明度
histtype: 直方图类型,‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’
 
返回值 :
n: 直方图向量,是否归一化由参数normed设定
bins: 返回各个bin的区间范围
patches: 返回每个bin里面包含的数据,是一个list
实例:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
np.random.seed(0) #随机种子点设置
mu = 100 #正态分布参数mu和sigma
sigma = 15
x = mu+sigma*np.random.randn(437) #随机生成x列
num_bins = 50 #柱子的个数
#-----------绘图--------------
fig,ax = plt.subplots()
#-------绘制直方图---------
n,bins,patches = ax.hist(x, num_bins, normed=1, facecolor='red', histtype='barstacked')
#--------normpdf()求取概率分布曲线------
y = mlab.normpdf(bins, mu, sigma)
ax.plot(bins, y, '--')#将概率曲线显示在图上
ax.set_xlabel('Smarts') #设置x轴的label
ax.set_ylabel('Probability density') #设置Y轴的label
ax.set_title(r'Histogram of IQ: $\mu=100$,$\sigma=15$') #设置图片标题
fig.tight_layout() #让图的位置更好的匹配窗口
plt.show()

输出结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息