鄭州微網(wǎng)站制作東莞seo網(wǎng)站管理
Python中采用.add_subplot繪制子圖的方法簡要舉例介紹
目錄
- Python中采用.add_subplot繪制子圖的方法簡要舉例介紹
- 一、Python中繪制子圖的方法
- 1.1 add_subplot函數(shù)
- 1.2 基本語法
- (1)add_subplot的核心語法
- (2)add_subplot在中編程中的主要程序段
- 二、使用.add_subplot繪制子圖舉例
- 2.1 問題描述
- 2.2 程序代碼
- 2.3 運行結(jié)果
在Python中中繪圖常會用到Matplotlib庫,本文講簡要舉例說明利用Matplotlib 庫中的函數(shù)add_subplot實現(xiàn)子圖的繪制,并說明其用法。
一、Python中繪制子圖的方法
1.1 add_subplot函數(shù)
作為Matplotlib 庫中的一個函數(shù)add_subplot,用于在畫布(figure)上添加子圖(subplot)。這個方法比較有用,可以幫助使用者在想要在一個圖中創(chuàng)建多個子圖。
1.2 基本語法
關(guān)于如何使用 add_subplot ,本小節(jié)給出了使用主要方法:
(1)add_subplot的核心語法
ax= fig.add_subplot(nrows, ncols, plot_number)
其中:
nrows: 表示網(wǎng)格中的行數(shù)。
ncols: 表示網(wǎng)格中的列數(shù)。
plot_number: 指定子圖的位置。
例如,fig.add_subplot(2, 3, 5)表示在2x3網(wǎng)格中的左下角放置一個子圖,則plot_number應為5。
(2)add_subplot在中編程中的主要程序段
import matplotlib.pyplot as plt
fig = plt.figure()
ax_n = fig.add_subplot(nrows, ncols, plot_number)
ax_n.plot(x_n, y_n)
plt.show()
二、使用.add_subplot繪制子圖舉例
2.1 問題描述
為了 在2*2的圖中繪制如下函數(shù)所表示的4個子圖,
{ y 1 = sin ? x + x y 2 = sin ? x 2 + 2 x y 3 = sin ? x 3 + 3 x y 4 = sin ? x 4 + 4 x \begin{cases} y_{1}=\sin x +x \\ y_{2}=\sin x^2 +2x \\ y_{3}=\sin x^3 +3x \\ y_{4}=\sin x^4 +4x\end{cases} ? ? ??y1?=sinx+xy2?=sinx2+2xy3?=sinx3+3xy4?=sinx4+4x?,其中 0 ≤ x < 2 π 0\le x <2\pi 0≤x<2π.
將使用Matplotlib工具庫中add_subplot的進行繪圖。
2.2 程序代碼
示例代碼
假設(shè)我們想在一個2x2的網(wǎng)格中繪制四個不同的圖表:
import matplotlib.pyplot as plt
import numpy as np# 1.數(shù)據(jù)準備x = np.linspace(0, 2* np.pi, 400)
y1 = np.sin(x )+x
y2 = np.sin(x ** 2)+2*x
y3 = np.sin(x ** 3)+3*x
y4 = np.sin(x ** 4)+4*x# 2.創(chuàng)建一個新的圖形對象
fig = plt.figure()# 2.1 在2x2的網(wǎng)格中添加子圖
ax1 = fig.add_subplot(2, 2, 1) # 左上
ax2 = fig.add_subplot(2, 2, 2) # 右上
ax3 = fig.add_subplot(2, 2, 3) # 左下
ax4 = fig.add_subplot(2, 2, 4) # 右下# 2.2.再各個子圖中繪制數(shù)據(jù)ax1.plot(x, y1)
ax1.set_title('Subplot 1')ax2.plot(x, y2)
ax2.set_title('Subplot 2')ax3.plot(x, y3)
ax3.set_title('Subplot 3')ax4.plot(x, y4)
ax4.set_title('Subplot 4')plt.show()
2.3 運行結(jié)果
比如將上述程序,在PyCharm中運行結(jié)果如下:
圖1 采用.add_subplot繪制子圖的運行結(jié)果