matplotlib画出直方图和密度图方法

前言

matplotlib处理经常能够用到的折线图、柱状图等,还可以画出直方图和密度图。

plt.hist()方法

matplotlib.pyplot.hist(x,bins = None,range = None,density = None,weights = None,cumulative = False,bottom = None,hist type =‘bar’,align =‘mid’,orientation =‘vertical’,rwidth = None,log = False,color = None,label = None,stacked = False,normed = None,*,data = None,** kwargs )
可以看到参数非常多,简单的介绍几个:
x : (n,)数组或序列(n,)数组
输入值,这需要单个数组或不需要具有相同长度的数组序列。

bins: int,默认是10,就是把数据分多少份的意思。
sequence, 可以给出bins的边缘如:[1, 2, 3, 4],分成的区间就是[1, 2)[2, 3)[3, 4]。

hist type : {‘bar’,‘barstacked’,‘step’,‘stepfilled’},可选,改变绘图样式。

rwidth:柱状图,每一个柱子的相对宽度

详情参考官方文档:传送门

代码demo

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas import Series, DataFrame

np.random.seed(666)

s = Series(np.random.randn(1000)) # 1000 个数据的分布
s.hist( rwidth = 0.9, bins = 5, histtype = 'stepfilled')
plt.show() # 见 图1

re = plt.hist(s, rwidth = 0.9, kind = 'kde')
'''
re 是一个元组

re[0] <class 'numpy.ndarray'> 出现的频率
[  6.  20.  81. 185. 265. 214. 151.  63.  10.   5.]

re[1] <class 'numpy.ndarray'>  出现的间隔
[-3.19551031 -2.5366076  -1.87770489 -1.21880218 -0.55989947  0.09900323
  0.75790594  1.41680865  2.07571136  2.73461407  3.39351678]
  
re[2] <a list of 10 Patch objects>  

'''
plt.show() # 见 图2
'''
第一个数值的频率是6,介于 -3.19551031 和 -2.5366076 之间
一次类推
'''

'''
参数设置:
bins 默认 10, 分多少份
color 选择颜色
orientation 默认垂直,可以选择水平

注意:将kind='kde',画出来的就是一个密度图,如:
s.plot(kind='kde') 就是一个密度图
'''

在之前提到对series画图中,可以使用 s.plot(),需要注意的是,将kind=‘kde’,画出来的就是一个密度图,如:
s.plot(kind=‘kde’) 就是一个密度图

图1:
在这里插入图片描述
图2:
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章