1. 程式人生 > >python—matplotlib資料視覺化例項註解系列-----之柱狀圖

python—matplotlib資料視覺化例項註解系列-----之柱狀圖

本文程式碼源自官方例項,部分進行了修改和註解方便學習和查詢。

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()


輸出結果: