一、什麼是Python hist
Python hist是Python中的一個數據可視化庫,它用於製作直方圖。直方圖是一個條形圖,用於展示數據集中值的頻率分布情況。Python hist使我們能夠輕鬆製作直方圖,並以最直觀的方式呈現數據集中的特徵和趨勢。
使用Python hist,我們能夠快速查看數據分布,識別異常值,探索數據分布的形狀、中心、離散程度等特性,並提取有關數據集的有用信息。
二、Python hist的基本語法
要使用Python hist,需要在程序中導入matplotlib庫。從matplotlib中導入pyplot子庫,可以使用pylot中的hist()函數。下面是hist()函數的基本語法:
import matplotlib.pyplot as plt
plt.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype='bar',
align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False,
normed=None, *, data=None, **kwargs)
其中,主要參數如下:
- x:用於繪製直方圖的數據
- bins:用於分組的組數
- range:數據取值範圍
- density:是否繪製密度曲線
- cumulative:是否繪製累計頻率直方圖
- align:直方圖對齊方式
- orientation:直方圖布局方式
- color:直方圖顏色
- label:圖例標籤
三、Python hist的使用實例
1. 繪製簡單直方圖
下面這個例子展示了如何使用Python hist創建一個簡單的直方圖,分組數為10,直方圖對齊方式為中間對齊:
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
# 創建5000個隨機數
x = np.random.randn(5000)
# 繪製直方圖
plt.hist(x, bins=10, align='mid', color='b', alpha=0.5)
plt.xlabel('Random Data')
plt.ylabel('Frequency')
plt.title('Simple Histogram')
# 顯示圖形
plt.show()
生成的直方圖如下圖所示:
2. 繪製比較直方圖
下面這個例子展示了如何繪製兩組數據的比較直方圖,分別為男性的身高和女性的身高。這個例子中,我們添加了圖例標籤以區分兩組數據:
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
# 男性身高數據
men_heights = [173, 177, 181, 185, 169, 173, 169, 167, 178, 172]
# 女性身高數據
women_heights = [164, 165, 168, 171, 174, 169, 166, 168, 165, 171]
# 繪製比較直方圖
plt.hist([men_heights, women_heights], bins=5, alpha=0.5, color=['g', 'm'], label=['Men', 'Women'])
plt.xlabel('Heights')
plt.ylabel('Frequency')
plt.legend(loc='upper right')
plt.title('Comparison Histogram')
# 顯示圖形
plt.show()
生成的直方圖如下圖所示:
四、總結
Python hist是Python中的一個數據可視化庫,用於製作直方圖。Python hist不僅能夠繪製簡單直方圖,還可以繪製比較直方圖等。使用Python hist能夠幫助我們更直觀地理解數據,從而發現數據集中的特徵和趨勢,發現異常值,提取有用信息並做出相應的數據分析與決策。
原創文章,作者:TVSQP,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/351527.html