Python使用matplotlib繪制圖形大全(曲線圖、條形圖、餅圖等)
一、什么是matplotlib
matplotlib 是一個用于創(chuàng)建靜態(tài)、動態(tài)和交互式可視化圖形的 Python 庫。它被廣泛用于數(shù)據(jù)可視化,并且可以與多種操作系統(tǒng)和圖形后端一起工作。matplotlib 提供了一套與 MATLAB 相似的命令 API,適合交互式制圖,也可以作為繪圖控件嵌入到其他應(yīng)用程序中。
matplotlib 的主要組成部分是 pyplot,它是一個類似于 MATLAB 的繪圖框架。pyplot 提供了一個 MATLAB 式的接口,可以隱式地創(chuàng)建圖形和軸,使得繪圖變得簡單。
以下是一個簡單的 matplotlib 使用示例,用于繪制一條簡單的折線圖:
import matplotlib.pyplot as plt
import numpy as np
# 創(chuàng)建數(shù)據(jù)
x = np.linspace(0, 10, 100)
y = np.sin(x)
# 創(chuàng)建圖形
plt.figure()
# 繪制折線圖
plt.plot(x, y, '-')
# 設(shè)置圖表標題和坐標軸標簽
plt.title("Simple Plot of Sine Function")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
# 顯示圖形
plt.show()
在這個例子中,我們首先導(dǎo)入了 matplotlib.pyplot 和 numpy。然后,我們創(chuàng)建了一組數(shù)據(jù) x 和 y,其中 y 是 x 的正弦函數(shù)。接下來,我們使用 plt.figure() 創(chuàng)建一個新的圖形,并使用 plt.plot() 繪制折線圖。最后,我們設(shè)置了圖表的標題和坐標軸標簽,并使用 plt.show() 顯示圖形。
這只是 matplotlib 的一個基本示例。該庫提供了許多其他功能,包括散點圖、條形圖、餅圖、3D 圖形、等高線圖等。此外,matplotlib 還支持自定義顏色、線型、標記等,以及添加圖例、網(wǎng)格等。
二、matplotlib 支持的圖形
matplotlib 是一個非常靈活的繪圖庫,支持繪制多種類型的圖形。以下是一些 matplotlib 支持的主要圖形類型:
- 線圖 (Line Plots): 最基本的圖形類型,用于顯示數(shù)據(jù)點的連接。
- 散點圖 (Scatter Plots): 用于顯示兩個變量之間的關(guān)系,通過點的分布來表示。
- 條形圖 (Bar Charts): 適用于展示分類數(shù)據(jù)的相對大小。
- 直方圖 (Histograms): 展示數(shù)據(jù)分布的統(tǒng)計圖,通常用于表示連續(xù)變量的分布情況。
- 餅圖 (Pie Charts): 用于表示整體中各部分的比例關(guān)系。
- 箱圖 (Box Plots): 用于展示數(shù)據(jù)的分布情況,包括中位數(shù)、四分位數(shù)、最大值、最小值以及可能存在的異常值。
- 面積圖 (Area Charts): 類似于線圖,但是下方區(qū)域會被填充顏色,用于表示數(shù)據(jù)隨時間的變化量。
- 等高線圖 (Contour Plots): 通常用于表示三維數(shù)據(jù)在二維平面上的投影,通過等高線展示數(shù)據(jù)點的密集程度。
- 熱力圖 (Heatmap): 通過顏色的深淺來表示數(shù)據(jù)矩陣中各個值的大小。
- 極坐標圖 (Polar Plots): 在極坐標系中展示數(shù)據(jù)點,常用于表示與角度相關(guān)的信息。
- 三維圖形 (3D Plots): 用于在三維空間中展示數(shù)據(jù)點的分布情況,可以創(chuàng)建三維散點圖、三維曲面圖等。
- 堆疊圖 (Stacked Plots): 適用于展示多個分類數(shù)據(jù)系列的累積效果,如堆疊條形圖或堆疊面積圖。
- 誤差條圖 (Error Bar Charts): 用于表示數(shù)據(jù)點的不確定性或變化范圍。
- 矢量場圖 (Vector Fields): 用于表示矢量數(shù)據(jù),如風(fēng)向或流體的流動方向。
- 流線圖 (Stream Plots): 類似于矢量場圖,但更側(cè)重于表示流體的流動路徑。
matplotlib 還支持許多其他高級和定制化的圖形,包括但不限于小提琴圖 (violin plots)、樹狀圖 (dendrograms)、雷達圖 (radar charts) 等。由于其強大的定制性和靈活性,matplotlib 已經(jīng)成為數(shù)據(jù)可視化的重要工具之一。
三、如何使用matplotlib
使用matplotlib進行數(shù)據(jù)可視化是一個相對直接的過程。以下是一個清晰、分點的指南,幫助您開始使用matplotlib:
1. 安裝matplotlib
首先,確保您已經(jīng)安裝了matplotlib庫。如果還沒有安裝,可以使用pip進行安裝:
pip install matplotlib
2. 導(dǎo)入matplotlib.pyplot
在Python腳本或Jupyter Notebook中,您需要導(dǎo)入matplotlib.pyplot模塊,通常我們使用別名plt來引用它:
import matplotlib.pyplot as plt
3. 準備數(shù)據(jù)
準備您要可視化的數(shù)據(jù)。這可以是實驗數(shù)據(jù)、統(tǒng)計數(shù)據(jù)或任何您想要展示的信息。
4. 繪制圖形
使用plt中的函數(shù)來繪制您想要的圖形。以下是一些常見圖形的繪制方法:
線圖:
plt.plot(x, y, label='Line 1') # x和y是數(shù)據(jù)點
散點圖:
plt.scatter(x, y) # x和y是數(shù)據(jù)點
條形圖:
plt.bar(x, y) # x是分類變量,y是對應(yīng)值
直方圖:
plt.hist(data, bins=10) # data是要統(tǒng)計的數(shù)據(jù),bins是分組數(shù)量
餅圖:
plt.pie(sizes, labels=labels) # sizes是各部分大小,labels是標簽
5. 定制圖形
您可以添加標題、軸標簽、圖例以及調(diào)整軸的范圍等:
plt.title('My Plot') # 添加標題
plt.xlabel('X Axis Label') # 添加X軸標簽
plt.ylabel('Y Axis Label') # 添加Y軸標簽
plt.legend() # 添加圖例
plt.xlim(0, 10) # 設(shè)置X軸范圍
plt.ylim(0, 100) # 設(shè)置Y軸范圍
6. 顯示或保存圖形
最后,使用plt.show()來顯示圖形,或者使用plt.savefig()來保存圖形到文件:
plt.show() # 顯示圖形
# 或者
plt.savefig('my_plot.png') # 保存圖形為PNG文件
7. (可選)使用subplots創(chuàng)建多個子圖
如果您想在同一個窗口中顯示多個圖形,可以使用plt.subplots():
fig, axs = plt.subplots(nrows=2, ncols=2) # 創(chuàng)建一個2x2的子圖網(wǎng)格 # 然后可以在每個子圖上進行繪制,例如: axs[0, 0].plot(x1, y1) # 在第一個子圖上繪圖 axs[0, 1].scatter(x2, y2) # 在第二個子圖上繪圖 # ...以此類推
注意事項:
- 確保您的數(shù)據(jù)格式正確,并且與所選的圖形類型兼容。
matplotlib具有高度的可定制性,您可以通過查閱官方文檔來了解更多高級功能和定制選項。- 在繪制復(fù)雜圖形時,考慮使用面向?qū)ο蟮姆绞絹聿僮鲌D形和軸對象,這可以提供更精細的控制。
四、常見圖形使用示例
下面我會通過具體的代碼示例來介紹matplotlib庫中常見圖形的繪制方法。
1. 線圖 (Line Plot)
線圖通常用于展示數(shù)據(jù)隨時間的變化趨勢。
import matplotlib.pyplot as plt
import numpy as np
# 創(chuàng)建數(shù)據(jù)
x = np.linspace(0, 10, 100)
y = np.sin(x)
# 繪制線圖
plt.plot(x, y)
plt.title('Line Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.grid(True)
plt.show()

2. 散點圖 (Scatter Plot)
散點圖用于展示兩個變量之間的關(guān)系。
# 創(chuàng)建數(shù)據(jù)
x = np.random.rand(50)
y = np.random.rand(50)
# 繪制散點圖
plt.scatter(x, y)
plt.title('Scatter Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.grid(True)
plt.show()

3. 條形圖 (Bar Chart)
條形圖適用于展示分類數(shù)據(jù)的相對大小。
# 創(chuàng)建數(shù)據(jù)
categories = ['Category1', 'Category2', 'Category3', 'Category4']
values = [23, 45, 56, 12]
# 設(shè)置字體為支持中文的字體,比如'SimHei'(黑體),確保你的系統(tǒng)中安裝了該字體
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用于正常顯示中文標簽
plt.rcParams['axes.unicode_minus'] = False # 用來正常顯示負號
# 繪制條形圖
plt.bar(categories, values, label='測試圖例')
plt.title('Bar Chart')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.legend()
plt.show()

4. 直方圖 (Histogram)
直方圖用于展示數(shù)據(jù)分布的統(tǒng)計圖。
# 創(chuàng)建數(shù)據(jù)(正態(tài)分布的隨機樣本)
data = np.random.rand(100)
print(data)
data = np.sort(data)
print(data)
# 繪制直方圖
plt.hist(data, bins=20, edgecolor='black', color='skyblue', alpha=0.7)
# 定制圖形
plt.title('Histogram of Data Distribution')
plt.xlabel('Value Range')
plt.ylabel('Frequency')
plt.grid(True)
# 顯示圖形
plt.show()

5. 餅圖 (Pie Chart)
餅圖用于表示整體中各部分的比例關(guān)系。
# 創(chuàng)建數(shù)據(jù)
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
# 繪制餅圖
plt.pie(sizes, labels=labels)
plt.title('Pie Chart')
plt.show()

6. 直方圖 2d
直方圖用于展示數(shù)據(jù)分布的統(tǒng)計圖。
# 創(chuàng)建數(shù)據(jù)
x = np.array([1, 2, 3, 4, 2, 2, 2, 1])
y = np.array([1, 2, 3, 4, 1, 2, 3, 4])
# 繪制直方圖
plt.hist2d(x, y, bins=[20, 20], cmap=plt.cm.jet)
plt.title('Histogram')
plt.xlabel('Value')
plt.ylabel('Frequency')
# 添加帶有標簽的顏色條
plt.colorbar(label='Counts')
plt.grid(True)
plt.show()

7. 面積圖(Area Plot)
面積圖是一種展示數(shù)據(jù)隨時間變化趨勢的圖形,通常用于顯示時間序列數(shù)據(jù)。
import matplotlib.pyplot as plt import numpy as np # 模擬數(shù)據(jù) x = np.arange(1, 6) y1 = np.random.randint(1, 5, 5) y2 = np.random.randint(1, 5, 5) # 繪制面積圖 # 繪制 y1 到 0 之間的區(qū)域 plt.fill_between(x, y1, color='blue', alpha=0.5, label='Area 1') # 繪制 y1 到 y2 之間的區(qū)域 plt.fill_between(x, y1, y2, color='red', alpha=0.5, label='Area 2') plt.legend() plt.show()

8. 熱力圖(Heatmap)
熱力圖通常用于顯示數(shù)據(jù)矩陣中各個元素值的大小,通過顏色來表示數(shù)值。
示例1
import matplotlib.pyplot as plt import numpy as np import seaborn as sns # 創(chuàng)建一個數(shù)據(jù)矩陣 data = np.random.rand(10, 12) # 繪制熱力圖 sns.heatmap(data, cmap='coolwarm') plt.show()

示例2
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# 創(chuàng)建一個假設(shè)的數(shù)據(jù)集
data = {
'Product': ['A', 'B', 'C', 'D', 'E'],
'January': np.random.randint(10, 100, 5),
'February': np.random.randint(10, 100, 5),
'March': np.random.randint(10, 100, 5),
'April': np.random.randint(10, 100, 5),
'May': np.random.randint(10, 100, 5),
'June': np.random.randint(10, 100, 5)
}
# 將數(shù)據(jù)轉(zhuǎn)換為Pandas DataFrame
df = pd.DataFrame(data)
df = df.set_index('Product')
# 繪制熱力圖
plt.figure(figsize=(10, 8))
sns.heatmap(df, annot=True, cmap='coolwarm', fmt='d', linewidth=0.5)
# 設(shè)置圖表標題和坐標軸標簽
plt.title('Monthly Sales Heatmap')
plt.xlabel('Month')
plt.ylabel('Product')
# 顯示圖表
plt.show()

9. 三維圖形(3D Plot)
Matplotlib也支持三維圖形的繪制,例如三維散點圖、三維曲面圖等。
import matplotlib.pyplot as plt import numpy as np # 創(chuàng)建3D坐標軸 fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # 模擬三維數(shù)據(jù)點 x = np.random.standard_normal(100) y = np.random.standard_normal(100) z = np.random.standard_normal(100) # 繪制三維散點圖 ax.scatter(x, y, z, c='b', marker='o') plt.show()

10. 堆疊圖(Stacked Plot)
堆疊圖通常用于展示不同類別數(shù)據(jù)隨某個變量的累積變化。
import matplotlib.pyplot as plt
import numpy as np
# 模擬數(shù)據(jù)
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
# 繪制男性數(shù)據(jù)堆疊圖
p1 = plt.bar(ind, menMeans, width, label='Men')
# 繪制女性數(shù)據(jù)堆疊圖,注意這里的bottom參數(shù),它使得女性數(shù)據(jù)的柱狀圖從男性數(shù)據(jù)的頂部開始繪制
p2 = plt.bar(ind, womenMeans, width, label='Women', bottom=menMeans)
plt.ylabel('Scores')
plt.title('Scores by group and gender')
# 設(shè)置X軸刻度
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
# 設(shè)置y軸刻度
plt.yticks(np.arange(0, 81, 10))
# 顯示圖例
plt.legend()
plt.show()

這些代碼示例展示了如何使用matplotlib繪制常見的圖形。您可以根據(jù)需要調(diào)整數(shù)據(jù)和圖形屬性來定制您的圖表。每個圖形類型都有許多可配置的選項,例如顏色、線型、標記樣式等,您可以通過查閱matplotlib的官方文檔來了解更多細節(jié)。
五、常用函數(shù)
在matplotlib庫中,有許多常用的函數(shù)用于數(shù)據(jù)可視化。以下是一些matplotlib.pyplot模塊中常用的函數(shù):
| 函數(shù) | 描述 | 使用示例 |
|---|---|---|
plot() | 繪制線圖 | plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) |
scatter() | 繪制散點圖 | plt.scatter([1, 2, 3, 4], [1, 4, 9, 16]) |
bar() | 繪制條形圖 | plt.bar([1, 2, 3, 4], [10, 15, 7, 10]) |
hist() | 繪制直方圖 | data = np.random.randn(1000); plt.hist(data, bins=30) |
pie() | 繪制餅圖 | plt.pie([10, 20, 30, 40], labels=['A', 'B', 'C', 'D']) |
boxplot() | 繪制箱線圖 | data = np.random.normal(100, 20, 200); plt.boxplot(data) |
imshow() | 顯示圖像 | image = np.random.rand(10, 10); plt.imshow(image) |
xlabel() | 設(shè)置X軸標簽 | plt.xlabel('Time') |
ylabel() | 設(shè)置Y軸標簽 | plt.ylabel('Amplitude') |
title() | 設(shè)置圖形標題 | plt.title('Sample Plot') |
xlim() | 設(shè)置X軸范圍 | plt.xlim(0, 10) |
ylim() | 設(shè)置Y軸范圍 | plt.ylim(-1, 1) |
xticks() | 設(shè)置X軸刻度 | plt.xticks([0, 1, 2, 3], ['zero', 'one', 'two', 'three']) |
yticks() | 設(shè)置Y軸刻度 | plt.yticks([-1, 0, 1], ['min', 'zero', 'max']) |
legend() | 添加圖例 | plt.plot([1, 2, 3], label='Line 1'); plt.legend() |
grid() | 添加網(wǎng)格線 | plt.grid(True) |
show() | 顯示圖形 | plt.plot([1, 2, 3], [1, 4, 9]); plt.show() |
savefig() | 保存圖形 | plt.plot([1, 2, 3], [1, 4, 9]); plt.savefig('plot.png') |
請注意,上述示例代碼僅為簡單演示函數(shù)的使用,實際應(yīng)用中可能需要根據(jù)具體需求調(diào)整參數(shù)和設(shè)置。另外,為了使示例代碼簡潔明了,這里沒有包含數(shù)據(jù)準備和圖形細節(jié)調(diào)整的部分。在實際應(yīng)用中,你通常需要先準備好數(shù)據(jù),并根據(jù)需要調(diào)整圖形的各種屬性(如線型、顏色、標簽等)。
參考
以上就是Python使用matplotlib繪制圖形大全(曲線圖、條形圖、餅圖等)的詳細內(nèi)容,更多關(guān)于Python matplotlib繪制圖形的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
YOLOv5構(gòu)建安全帽檢測和識別系統(tǒng)使用詳解
這篇文章主要為大家介紹了YOLOv5構(gòu)建安全帽檢測和識別系統(tǒng)使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04
Python Numpy實現(xiàn)修改數(shù)組形狀
NumPy(Numerical Python)是Python中用于處理數(shù)組和矩陣的重要庫,它提供了豐富的功能,用于科學(xué)計算,本文主要介紹了如何使用NumPy提供的方法來改變數(shù)組的形狀,感興趣的可以了解下2023-11-11
解決python執(zhí)行不輸出系統(tǒng)命令彈框的問題
今天小編就為大家分享一篇解決python執(zhí)行不輸出系統(tǒng)命令彈框的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06

