1.1 plt.figure()函數(shù)語法介紹
figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True)
1、num:圖像編號或名稱,數(shù)字為編號 ,字符串為名稱
2、figsize:指定figure的寬和高,單位為英寸;
3、dpi參數(shù)指定繪圖對象的分辨率,即每英寸多少個像素;
4、facecolor:背景顏色;
5、edgecolor:邊框顏色;
6、frameon:是否顯示邊框。
figure函數(shù)就相當于畫畫所用的畫布,在此簡單描繪一個曲線來說明
1.2 figure實例
import matplotlib.pyplot as plt
import numpy as np
#np.linspace(start, stop, num)num是起點終點間隔總點數(shù)
x = np.linspace(0, 50, 1000)
y = np.cos(x)
fig = plt.figure()
plt.plot(x, y)
# plt.show()的作用就是將畫布及其所畫內(nèi)容顯示出來
plt.show()
結(jié)果顯示:
關(guān)于linespace的語法說明:
np.linspace(start, stop, num, endpoint, retstep, dtype)
1、star和stop為起始和終止位置,均為標量
2、num為包括start和stop的間隔點總數(shù),默認為50
3、endpoint為bool值,為False時將會去掉最后一個點計算間隔
4、restep為bool值,為True時會同時返回數(shù)據(jù)列表和間隔值
5、dtype默認為輸入變量的類型,給定類型后將會把生成的數(shù)組類型轉(zhuǎn)為目標類型
***通常是用前三個參數(shù)就可以了
2.1 subplot函數(shù)及其語法說明
subplot(a,b,c)
1、a是subplot的行數(shù);
2、b是subplot的列數(shù);
3、c是subplot中子圖的序列號;
2.2 用subplot畫多個子圖
import numpy as np
# 依次輸出函數(shù)f(x)=x、f(x)=x**2、f(x)=sin(x)、f(x)=tan(x)的圖像
x = np.linspace(0, 10, 100)
x1 = x
x2 = x ** 2
x3 = np.sin(x)
x4 = np.tan(x)
fig = plt.figure()
# 此處的221指輸出模式是兩行兩列,且輸出對應的第一個子圖
plt.subplot(221)
plt.plot(x, x1)
plt.subplot(222)
plt.plot(x, x2)
plt.subplot(223)
plt.plot(x, x3)
plt.subplot(224)
plt.plot(x, x4)
plt.show()
運行程序后輸出的結(jié)果為:
根據(jù)上面程序可以看出,每一個subplot()只可以輸出一個子圖,要想輸出多個子圖,就需要使用對應的多個subplot()函數(shù)。
如果想用一個函數(shù)就直接輸出多個子圖,可以使用subplots()函數(shù)實現(xiàn)。
3.1 subplots函數(shù)介紹
在此用subplots()函數(shù)來實現(xiàn)同樣的2*2類型的子圖描繪,實現(xiàn)代碼如下:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
# 劃分2*2子圖
fig, axes = plt.subplots(2, 2)
ax1 = axes[0, 0]
ax2 = axes[0, 1]
ax3 = axes[1, 0]
ax4 = axes[1, 1]
# 作圖f(x)=x
ax1.plot(x, x)
# 作圖f(x)=x**2
ax2.plot(x, x ** 2)
ax2.grid(color='r', linestyle='--', linewidth=1, alpha=0.3)
# 作圖f(x)=sin(x)
ax3.plot(x, np.sin(x))
# 作圖f(x)=tan(x)
ax4.plot(x, np.tan(x))
plt.show()
顯示結(jié)果如下:
由此,我們可以看到subplots()函數(shù)同樣實現(xiàn)了四個子圖的描繪,在功能上和2.2節(jié)所用的subplot()函數(shù)達到了一樣的效果。文章來源:http://www.zghlxwxcb.cn/news/detail-703316.html
4.1 使用add_axes函數(shù)繪制圖中圖
import numpy as np
import matplotlib.pyplot as plt
# 新建figure
fig = plt.figure()
# 定義數(shù)據(jù)
x = np.linspace(0, 10, 100)
y1=np.exp(x)
y2 = np.sin(x)
# 新建區(qū)域a
left, bottom, width, height = 0, 0, 1, 1
# 繪制圖像y1
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y1, 'b')
ax1.set_title('y1=exp(x)')
# 設置新增區(qū)域b,嵌套在a圖內(nèi)
left, bottom, width, height = 0.3, 0.5, 0.4, 0.4
# 繪制圖像y2
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(x, y2, 'g')
ax2.set_title('y2=sin(x)')
plt.show()
得到的輸出結(jié)果為:文章來源地址http://www.zghlxwxcb.cn/news/detail-703316.html
到了這里,關(guān)于plt.figure、plt.subplot介紹以及繪制圖中圖(含代碼)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!