Matplotlib使用

Matplotlib 是支持 Python 語言的開源繪圖庫,因為其支持豐富的繪圖類型、簡單的繪圖方式以及完善的接口文檔,深受 Python 工程師、科研學(xué)者、數(shù)據(jù)工程師等各類人士的喜歡。Matplotlib擁有著十分活躍的社區(qū)以及穩(wěn)定的版本迭代。

1、簡單圖形繪制

使用 Matplotlib 提供的面向?qū)ο?API,需要導(dǎo)入 pyplot模塊,并約定簡稱為 plt

from matplotlib import pyplot as plt

接下來我會繪制一個簡單的山峰圖:

plt.plot([1, 2, 3, 2, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1])
plt.show()

屏幕快照 2019-06-16 下午11.24.50.png

2、繪制正余弦圖(具體如圖)

sin_cos_plot.png

實例代碼

import numpy as np 
x = np.linspace(-np.pi, np.pi, 200)
C , S = np.cos(x), np.sin(x)
# 設(shè)置顏色、線寬、樣式
plt.plot(x, C, color='blue', linewidth=2.0, linestyle='-')
plt.plot(x, S, color='r', linewidth=2.0, linestyle='-')

# 設(shè)置坐標(biāo)長度
plt.xlim(x.min()*1.1, x.max()*1.1)
plt.ylim(C.min()*1.1, C.max()*1.1)

# 設(shè)置坐標(biāo)刻度和標(biāo)簽
plt.xticks((-np.pi, -np.pi/2.0, np.pi/2.0, np.pi), (r'$-\pi$', r'$-\pi/2$', r'$\pi/2.0$', r'$\pi$'))

plt.yticks([-1, -0.5, 0, 0.5, 1])

# 坐標(biāo)軸處理

# 獲取坐標(biāo)軸
ax = plt.gca() # gca 代表當(dāng)前坐標(biāo)軸,
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# set_ticks_position() 設(shè)置坐標(biāo)軸的刻度線的顯示位置
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0)) # 設(shè)置下方坐標(biāo)軸位置 

ax.yaxis.set_ticks_position("left")
ax.spines['left'].set_position(('data', 0)) # 設(shè)置左側(cè)坐標(biāo)軸位置

# 添加圖例
plt.legend(loc='upper left')

# 標(biāo)記2/3*pi 正弦余弦值
t = 2 * np.pi / 3
# 
plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=1.5, linestyle='--')

# 畫出標(biāo)識點
plt.scatter([t,], [np.cos(t),], 50, color='blue')
# 畫出cos(t)的值
plt.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$', xy=(t, np.cos(t)), xycoords='data', xytext=(-90, -50), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=.2"))

# 畫sin(t)的值
plt.scatter([t,],[np.sin(t),], 50, color='red')
plt.annotate(r'$sin(\frac{2\pi}{3})=\frac{sqrt(3)}{2}$', xy=(t, np.sin(t)), xycoords='data', xytext=(60, 50), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=0.5"))


3、使用gridspec 實現(xiàn)復(fù)雜子圖布局

grid_spec_plot.png
# 使用grdspe實現(xiàn)復(fù)雜子圖布局

import matplotlib.gridspec as gridspec

plt.figure(figsize=(18, 4))
G = gridspec.GridSpec(3, 3)

axes_1 = plt.subplot(G[0,:]) # 占用第一行,所有的列
plt.xticks(())
plt.yticks(())
plt.text(0.5, 0.5, 'Axes 01', ha='center', va='center', size=24, alpha=5)

axes_2_1 = plt.subplot(G[1:,0]) # 占用第二行,第一列
plt.xticks(())
plt.yticks(())
plt.text(0.5, 0.5, 'Axes 02_01', ha='center', va='center', size=24, alpha=5)

axes_2_3 = plt.subplot(G[1:,-1]) # 占用第二行開始之后的所有行,最后一列
# axes_2_2 = plt.subplot(G[1:,1]) # 占用第二行開始之后的所有行,第二列之后的所有列
plt.xticks(())
plt.yticks(())
plt.text(0.5, 0.5, 'Axes 02_03', ha='center', va='center', size=24, alpha=5)

# 占用第二行第二列
axes_2_2 = plt.subplot(G[1,-2])
plt.xticks(())
plt.yticks(())
plt.text(0.5, 0.5, 'Axes 02_02', ha='center', va='center', size=24, alpha=5)

axes_3_1 = plt.subplot(G[-1,-2]) # 占用倒數(shù)第一行,倒數(shù)第二列
plt.xticks(())
plt.yticks(())
plt.text(0.5, 0.5, 'Axes 03_02', ha='center', va='center', size=24, alpha=5)

4、Matplotlib內(nèi)置坐標(biāo)軸刻度

  • NullLocater: 不顯示坐標(biāo)刻度標(biāo)簽,只顯示坐標(biāo)刻度
  • MultipleLocator: 以固定的步長顯示多個坐標(biāo)標(biāo)簽
  • FixedLocator: 以列表形式顯示固定的坐標(biāo)標(biāo)簽
  • IndexLocator: 以 offset為起始位置,每隔base步長就畫一個坐標(biāo)標(biāo)簽
  • LinearLocator: 把坐標(biāo)軸的長度均分為numticks個數(shù),顯示坐標(biāo)標(biāo)簽
  • LogLocator: 以對數(shù)為步長顯示刻度的標(biāo)簽
  • MaxNLocator: 從提供的刻度標(biāo)簽列表里,顯示出最大不超過nbins個數(shù)標(biāo)簽
  • AutoLocator: 自動顯示刻度標(biāo)簽

除內(nèi)置標(biāo)簽外,我們也可以繼承Matplotlib.tiker.Locator類來實現(xiàn)自定義樣式的刻度標(biāo)簽。

# 刻度標(biāo)簽
def tickline():
    plt.xlim(0, 10), plt.ylim(-1, 1), plt.yticks([])
    
    ax = plt.gca()
    ax.spines['right'].set_color('none')
    ax.spines['left'].set_color('none')
    ax.spines['top'].set_color('none')
    
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['bottom'].set_position((('data'), 0))
    ax.yaxis.set_ticks_position('none')
    ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))
    # 設(shè)置刻度標(biāo)簽文本字體大小
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontsize(16)
    ax.plot(np.arange(11), np.zeros(11))
    return ax

locators = [
    'plt.NullLocator()',
    'plt.MultipleLocator(base=1.0)',
    'plt.FixedLocator(locs=[0, 2, 8, 9, 10])',
    'plt.IndexLocator(base=3, offset=1)',
    'plt.LinearLocator(numticks=5)',
    'plt.LogLocator(base=2, subs=[1.0])',
    'plt.MaxNLocator(nbins=3, steps=[1, 3, 5, 7, 9, 10])',
    'plt.AutoLocator()',
]

n_locators = len(locators)

# 計算圖形對象大小
size = 1024, 60 * n_locators
dpi = 72.0
figsize = size[0] / float(dpi), size[1]/float(dpi)

fig = plt.figure(figsize=figsize, dpi=dpi)

fig.patch.set_alpha(0) 
for i, locator in enumerate(locators):
    plt.subplot(n_locators, 1, i+1)
    ax = tickline()
    ax.xaxis.set_major_locator(eval(locator))
    plt.text(5, 0.3, locator[3:], ha='center', size=16)
plt.subplots_adjust(bottom=0.01, top=0.99, left=0.1, right=0.99)

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

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

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