首頁技術文章正文

使用hist()繪制直方圖

更新時間:2022-02-22 來源:黑馬程序員 瀏覽量:

  使用pyplot的hist()函數(shù)可以快速繪制直方圖,hist()函數(shù)的語法格式如下所示:

hist(x, bins=None, range=None, density=None, weights=None,
     cumulative=False, bottom=None, histtype='bar', align='mid',
     orientation='vertical', rwidth=None, log=False, label=None,
     stacked=False, normed=None, *,data=None, **kwargs)

  該函數(shù)常用參數(shù)的含義如下。

  ·x:表示x軸的數(shù)據(jù),可以為單個數(shù)組或多個數(shù)組的序列。

  ·bins:表示矩形條的個數(shù),默認為10。

  ·range:表示數(shù)據(jù)的范圍。若沒有提供range參數(shù)的值,則數(shù)據(jù)范圍為(x.min(),x.max())。

  ·cumulative:表示是否計算累計頻數(shù)或頻率。

  ·histtype:表示直方圖的類型,支持'bar'、'barstacked'、'step'、'stepfilled'四種取值,其中'bar'為默認值,代表傳統(tǒng)的直方圖;'barstacked'代表堆積直方圖;'step'代表未填充的線條直方圖;'stepfilled'代表填充的線條直方圖。

  ·align:表示矩形條邊界的對齊方式,可設置為'left'、'mid'或'right',默認為'mind'。

  ·orientation:表示矩形條寬度的百分比,默認為0。若histtype的值為'step'或'stepfilled',則直接忽略rwidth參數(shù)的值。

  ·stacked:表示是否將多個矩形條以堆積形式擺放。

  例如,繪制一個具有8個矩形條填充的線條直方圖,代碼如下。

import matplotlib.pyplot as plt
import numpy as np
# 準備50個隨機測試數(shù)據(jù)
scores = np.random.randint(0,100,50)
# 繪制直方圖
plt.hist(scores, bins=8, histtype='stepfilled')
plt.show()

運行程序,效果如圖2-14所示。

1645510644655_填充的線條直方圖示例.jpg

圖2-14 填充的線條直方圖示例

分享到:
在線咨詢 我要報名
和我們在線交談!