Matplotlib中怎么創(chuàng)建直方圖

小億
84
2024-05-11 18:32:52
欄目: 編程語言

要?jiǎng)?chuàng)建直方圖,可以使用matplotlib庫中的hist()函數(shù)。以下是一個(gè)簡(jiǎn)單的示例代碼:

import matplotlib.pyplot as plt

# 數(shù)據(jù)
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]

# 創(chuàng)建直方圖
plt.hist(data, bins=5, color='skyblue', edgecolor='black')

# 添加標(biāo)題和標(biāo)簽
plt.title('Histogram of Data')
plt.xlabel('Value')
plt.ylabel('Frequency')

# 顯示圖形
plt.show()

在這個(gè)例子中,我們首先導(dǎo)入matplotlib庫,然后定義了一個(gè)包含數(shù)據(jù)的列表。然后使用hist()函數(shù)創(chuàng)建直方圖,設(shè)置了bins參數(shù)來指定直方圖的箱數(shù),color參數(shù)來設(shè)置直方圖的顏色,edgecolor參數(shù)來設(shè)置箱邊的顏色。接著設(shè)置了標(biāo)題和標(biāo)簽,最后調(diào)用show()函數(shù)顯示圖形。

0