Matplotlib

概念

Matplotlib將數(shù)據(jù)繪制為Figure,包含:

  • Figure:圖形??珊鄠€(gè)axes、特殊Artists(title, legend等)以及canvas(實(shí)際繪圖的對(duì)象,對(duì)用戶不可見)。
  • Axes:坐標(biāo)系。一個(gè)將點(diǎn)表示為坐標(biāo)的區(qū)域。只能屬于一個(gè)figure。含2~3個(gè)axis,每個(gè)axis對(duì)應(yīng)的Label,以及一個(gè)title。Axes類及其方法是OO(面向?qū)ο螅╋L(fēng)格的主要接口。
  • Axis:坐標(biāo)軸。設(shè)定數(shù)據(jù)的范圍,生成ticks(坐標(biāo)軸上的marks)和ticklabels(ticks對(duì)應(yīng)的標(biāo)識(shí))。
  • Artist:所有可見的組件都屬于Artist,包括Figure、Axes、Axis、title、legend等。當(dāng)渲染figure時(shí),所有artists會(huì)在canvas上繪制出來。

子圖和子坐標(biāo)系:

  • SubFigure:Figure子類,一個(gè)figure可含多個(gè)subfigure,有figure相同的方法,但不能單獨(dú)打印。
  • add_subfigure:創(chuàng)建1個(gè)SubFigure實(shí)例。Figure.add_subfigureSubFigure.add_subfigure。
  • subfigures:創(chuàng)建r行c列個(gè)subfigures。Figure.subfigures、SubFigure.subfigures。
  • SubplotBase:Axes子類,附加生成和操作Axes的方法。
  • subplots(r,c):創(chuàng)建r行c列個(gè)SubplotBase實(shí)例。pyplot.subplots、Figure.subplots
  • subplot(r,c,n):創(chuàng)建r行c列個(gè)SubplotBase實(shí)例中第n個(gè)SubplotBase實(shí)例(展開成1維后第n個(gè))。pyplot.subplotFigure.add_subplot。

畫圖

顯式隱式

方式1,顯式的創(chuàng)建Figure和Axes,使用Axes的接口繪圖。

fig, ax = plt.subplots()  # Create a figure containing a single axes.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])  # Plot some data on the axes.
fig.show()
fig = plt.figure()  # Create a figure without axes.
ax = Axes(fig, (0,0,0,0))  # Create an axes in the figure.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
fig.show()
fig = Figure()  # Create a figure without axes.
ax = fig.add_subplot()  # Ass an axes into the figure.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
fig.show()
fig = Figure()  # Create a figure without axes.
# 等價(jià)于fig.add_axes(rect)
ax = Axes(fig, (0,0,0,0))  # Create an axes in the figure.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
# 這種方式show()無效
ax = plt.axes()
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.show()

方式2,隱式的創(chuàng)建figure和axes(若當(dāng)前存在一個(gè)axes,則使用該axes,否則創(chuàng)建axes以及所需的figure),使用pyplot的接口繪圖(Axes的每個(gè)繪圖接口都有對(duì)應(yīng)的pyplot接口)。

plt.plot([1, 2, 3, 4], [1, 4, 2, 3])  # Similar to MATLAB plot.
plt.show()

風(fēng)格

OO風(fēng)格,建議用于大型項(xiàng)目,邏輯清晰:

x = np.linspace(0, 2, 100)  # Sample data.

# Note that even in the OO-style, we use `.pyplot.figure` to create the figure.
fig, ax = plt.subplots()  # Create a figure and an axes.
ax.plot(x, x, label='linear')  # Plot some data on the axes.
ax.plot(x, x**2, label='quadratic')  # Plot more data on the axes...
ax.plot(x, x**3, label='cubic')  # ... and some more.
ax.set_xlabel('x label')  # Add an x-label to the axes.
ax.set_ylabel('y label')  # Add a y-label to the axes.
ax.set_title("Simple Plot")  # Add a title to the axes.
ax.legend()  # Add a legend.

pyplot風(fēng)格,建議用于交互式編程(如Notebook):

x = np.linspace(0, 2, 100)  # Sample data.

plt.plot(x, x, label='linear')  # Plot some data on the (implicit) axes.
plt.plot(x, x**2, label='quadratic')  # etc.
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend()

不推薦混用兩種風(fēng)格,如有需要:

  • 獲取當(dāng)前figure:plt.gcf()
  • 獲取當(dāng)前axes:plt.gca()。

設(shè)置Figure

創(chuàng)建figure的幾種方式:

plt.figure(figsize=(6.4,4.8), dpi=100.0)

  • figsize,(width, height) inches(分辨率單位),一般默認(rèn)為(6.4,4.8),notebook上默認(rèn)為(6,4)。
  • dpi,dots per inch(每個(gè)inch的點(diǎn)數(shù)),一般默認(rèn)為100.0,notebook上默認(rèn)為72。

示例

plt.figure(figsize=[4*2,4*2],dpi=72.0)#default: [6.4, 4.8] 100.0
plt.subplot(2,2,1),plt.imshow(img0),plt.title("original")
plt.subplot(2,2,2),plt.imshow(crop1),plt.title("train1")
plt.subplot(2,2,3),plt.imshow(crop2),plt.title("train2")
plt.subplot(2,2,4),plt.imshow(crop3),plt.title("test1")
plt.tight_layout()
plt.savefig(os.path.join(OUTPUT_PATH, 'random_crop.pdf'))
plt.show()

Scipy.stats繪制方差,當(dāng)aa.shape[0]=1時(shí),方差不存在,也不會(huì)體現(xiàn)在圖上:

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
aa = np.array([[0,1,2,3,4],[0.1,1,2.1,3.2,4.1]])
e = stats.sem(aa, axis=0)
m = np.mean(aa, axis=0)
plt.plot(m)
plt.fill_between(range(5), m-e,m+e, alpha=0.3)
plt.show()

旋轉(zhuǎn)坐標(biāo)軸的標(biāo)簽:

plt.xticks(range(3), ["Zi 1", "Zi 2" ,"Zi 3"], rotation=-45)
# 或
plt.setp(plt.xticks(), rotation=-45, rotation_mode="anchor")

colorbar,支持多個(gè)子圖共享colorbar:

import matplotlib
import matplotlib.pyplot as plt

cmap = matplotlib.colormaps['jet']
fig, axes = plt.subplots(6, 1)
im = None
for i in range(6):
    im = axes[i].imshow(y[i].T, cmap=cmap, interpolation='nearest', aspect='auto')
    axes[i].set_ylabel('t')
for i in range(5):
    axes[i].set_xticks([])
axes[-1].set_xlabel('x')
fig.tight_layout()  # tight_layout放在colorbar之前,否則colorbar會(huì)與其他axes重疊
cbar = fig.colorbar(im, ax=axes)  # 通過axes列表指定覆蓋的axes
cbar.set_label('u(t,x)')
fig.savefig(f'images/result.jpg')
fig.show()

繪制直方圖

繪制grad、weight、activation的分布圖,橫坐標(biāo)為2的冪次,縱坐標(biāo)啟用了log(10的冪次)

import numpy as np
import matplotlib.pyplot as plt

g = np.random.normal(loc=2**-8, scale=2**-8, size=(8192*8))
w = np.random.normal(loc=0, scale=2**-6, size=(8192*8))
a = np.random.normal(loc=0, scale=2**-0, size=(8192*8))
g = np.log2(g)
w = np.log2(w)
a = np.log2(a)

x = [g, w, a]
colors = ['r', 'y', 'b']
plt.hist(x, bins=50, histtype='bar', color=colors, label=colors, log=True)
# plt.xlim((-45, 5))
plt.xlabel('Exp')
plt.ylabel('Frequency')
plt.legend(['Gradient', 'Weight', 'Activation'])
plt.show()

繪制動(dòng)畫

ArtistAnimation方式:

cmap = matplotlib.colormaps['jet']
fig, ax = plt.subplots(1,3)
ims = []
for i in range(10):
    ax[0].set_title(f'Label')
    # 若要固定每幀colorbar的坐標(biāo)軸數(shù)值范圍,可設(shè)定vmin、vmax:
    # imshow(yy[i], cmap=cmap, vmin=0, vmax=1, animated=True)
    im0 = ax[0].imshow(yy[i], cmap=cmap, animated=True)
    ax[1].set_title(f'Prediction')
    im1 = ax[1].imshow(yp[i], cmap=cmap, animated=True)
    ax[2].set_title(f'Error')
    im2 = ax[2].imshow(ye[i], cmap=cmap, animated=True)
    fig.suptitle(f't={i}')
    fig.tight_layout()
    fig.colorbar(im1, ax=ax[2])
    ims.append([im0, im1, im2])

# blit必須為True,否則畫出的圖為空
ani = animation.ArtistAnimation(fig, ims, interval=200, blit=True, repeat_delay=1000)
ani.save('animation.gif')
plt.show()

FuncAnimation方式:

cmap = matplotlib.colormaps['jet']
fig, ax = plt.subplots(1,3, figsize=[7, 3])

ax[0].set_title(f'Label')
# 若要固定每幀colorbar的坐標(biāo)軸數(shù)值范圍,可設(shè)定vmin、vmax:
# imshow(yy[0], cmap=cmap, vmin=0, vmax=1)
im0 = ax[0].imshow(yy[0], cmap=cmap)
ax[1].set_title(f'Prediction')
im1 = ax[1].imshow(yp[0], cmap=cmap)
ax[2].set_title(f'Error')
im2 = ax[2].imshow(ye[0], cmap=cmap)
title = fig.suptitle(f't=0')
fig.tight_layout()
fig.colorbar(im1, ax=ax)

def animate(i):
    y, p, e = yy[..., i, :], yp[..., i, :], ye[..., i, :]
    im0.set_data(y)
    im1.set_data(p)
    im2.set_data(e)
    # 若要固定每幀colorbar的坐標(biāo)軸數(shù)值范圍,結(jié)合上方,
    # 設(shè)定set_clim(0, 1),或不設(shè)置。
    im0.set_clim(np.min(y), np.max(y))
    im1.set_clim(np.min(p), np.max(p))
    im2.set_clim(np.min(e), np.max(e))
    title.set_text(f't={i}')

ani = animation.FuncAnimation(fig, animate, interval=200, blit=False, frames=10,
                              repeat_delay=1000)
ani.save('animation.gif')
plt.show()

其他

若訓(xùn)練進(jìn)程(包括nohup &啟動(dòng)的進(jìn)程),總是因matplotlib異常中斷,則:

import matplotlib.pyplot as plt
matplotlib.use('Agg')
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容