plt.hist()
用於畫直方圖。
參數列表:
plt.hist(x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, normed=None)
- x:指定要繪制直方圖的數據;輸入值,這需要一個數組或者一個序列,不需要長度相同的數組。
- bins:指定直方圖條形的個數;
- range:指定直方圖數據的上下界,默認包含繪圖數據的最大值和最小值;
- density:布爾,可選。如果"True",返回元組的第一個元素將會將計數標准化以形成一個概率密度,也就是說,直方圖下的面積(或積分)總和為1。這是通過將計數除以數字的數量來實現的觀察乘以箱子的寬度而不是除以總數數量的觀察。如果疊加也是“真實”的,那么柱狀圖被規范化為1。(替代normed)
- weights:該參數可為每一個數據點設置權重;
- cumulative:是否需要計算累計頻數或頻率;
- bottom:可以為直方圖的每個條形添加基准線,默認為0;
- histtype:指定直方圖的類型,默認為bar,除此還有’barstacked’, ‘step’, ‘stepfilled’;
- align:設置條形邊界值的對其方式,默認為mid,除此還有’left’和’right’;
- orientation:設置直方圖的擺放方向,默認為垂直方向;
- rwidth:設置直方圖條形寬度的百分比;
- log:是否需要對繪圖數據進行log變換;
- color:設置直方圖的填充色;
- label:設置直方圖的標簽,可通過legend展示其圖例;
- stacked:當有多個數據時,是否需要將直方圖呈堆疊擺放,默認水平擺放;
- normed:是否將直方圖的頻數轉換成頻率;(棄用,被density替代)
- alpha:透明度,浮點數。
返回值:
- n:直方圖的值
- bins:返回各個bin的區間范圍
- patches:返回每個bin的信息
import numpy as np import matplotlib.pyplot as plt np.random.seed(19260801) mu1, sigma1 = 100, 15 mu2, sigma2 = 80, 15 x1 = np.random.normal(mu1,sigma1,10000) # (均值,標准差,個數) x2 = np.random.normal(mu2,sigma2,10000) # the histogram of the data # 50:將數據分成50組 # color:顏色;alpha:透明度 # density:是密度而不是具體數值 n1, bins1, patches1 = plt.hist(x1, bins=50, density=True, color='g', alpha=1) n2, bins2, patches2 = plt.hist(x2, bins=50, density=True, color='r', alpha=0.2) plt.show()
添加分布曲線
根據plt.hist()返回值,很容易畫出分布曲線
#print(len(bins1)) #51 #print(len(n1)) #50 plt.plot(bins1[:-1],n1,'--') plt.plot(bins2[:-1],n2,'--')
多類型直方圖
import numpy as np import matplotlib.pyplot as plt # 生成3組值,每組的個數可以不一樣 x1,x2,x3 = [np.random.randn(n) for n in [10000, 5000, 2000]] plt.figure(figsize=(8,5)) # 在 ax.hist 函數中先指定圖例 label 名稱 plt.hist([x1, x2, x3], bins=10, density=True, histtype='bar') # 通過 ax.legend 函數來添加圖例 plt.legend(list("ABC")) plt.show()
添加說明信息
添加title
你可以給圖示或圖添加標題。但是默認不支持中文,需要自己添加中文字體。
windows的字體文件放在 C:\Windows\Fonts
,通過fontproperties設置字體,fontsize設置字體大小.
import matplotlib songTi = matplotlib.font_manager.FontProperties(fname='C:\\Windows\\Fonts\\msyh.ttc') plt.title("多類型直方圖",fontproperties=songTi,fontsize=12)
添加文字、網格、軸標簽及軸范圍
import numpy as np import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) # the histogram of the data n, bins, patches = plt.hist(x, 50, density=True, facecolor='g', alpha=0.75) plt.xlabel('Smarts') plt.ylabel('Probability') plt.title('Histogram of IQ') plt.text(60, .025, r'$\mu=100,\ \sigma=15$') #(x,y,str,...) plt.xlim(40, 160) plt.ylim(0, 0.03) plt.grid(True) plt.show()
參考鏈接: