前言
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: