首頁技術(shù)文章正文

使用hist()繪制直方圖

更新時(shí)間: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ù),可以為單個(gè)數(shù)組或多個(gè)數(shù)組的序列。

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

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

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

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

  ·align:表示矩形條邊界的對(duì)齊方式,可設(shè)置為'left'、'mid'或'right',默認(rèn)為'mind'。

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

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

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

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

運(yùn)行程序,效果如圖2-14所示。

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

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

分享到:
在線咨詢 我要報(bào)名
和我們?cè)诰€交談!