matplotlib各部件詳解

首先一幅Matplotlib的圖像組成部分介紹。

在matplotlib中,整個圖像爲一個Figure對象。在Figure對象中可以包含一個或者多個Axes對象。每個Axes(ax)對象都是一個擁有自己座標系統的繪圖區域。所屬關係如下:

下面以一個直線圖來詳解圖像內部各個組件內容:

其中:title爲圖像標題,Axis爲座標軸, Label爲座標軸標註,Tick爲刻度線,Tick Label爲刻度註釋。各個對象關係可以梳理成以下內容:

圖像中所有對象均來自於Artist的基類。

上面基本介紹清楚了圖像中各個部分的基本關係,下面着重講一下幾個部分的詳細的設置。

一個"Figure"意味着用戶交互的整個窗口。在這個figure中容納着"subplots"。

當我們調用plot時,matplotlib會調用gca()獲取當前的axes繪圖區域,而且gca反過來調用gcf()來獲得當前的figure。如果figure爲空,它會自動調用figure()生成一個figure, 嚴格的講,是生成subplots(111)

Figures

Subplots

plt.subplot(221) # 第一行的左圖
plt.subplot(222) # 第一行的右圖
plt.subplot(212) # 第二整行
plt.show()

注意:其中各個參數也可以用逗號,分隔開。第一個參數代表子圖的行數;第二個參數代表該行圖像的列數; 第三個參數代表每行的第幾個圖像。

另外:fig, ax = plt.subplots(2,2),其中參數分別代表子圖的行數和列數,一共有 2x2 個圖像。函數返回一個figure圖像和一個子圖ax的array列表。

補充:gridspec命令可以對子圖區域劃分提供更靈活的配置。

Tick Locators

Tick Locators 控制着 ticks 的位置。比如下面:

ax = plt.gca()
ax.xaxis.set_major_locator(eval(locator))

一些不同類型的locators:

代碼如下:

import numpy as np
import matplotlib.pyplot as plt


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))
ax.plot(np.arange(11), np.zeros(11))
return ax

locators = [
'plt.NullLocator()',
'plt.MultipleLocator(1.0)',
'plt.FixedLocator([0, 2, 8, 9, 10])',
'plt.IndexLocator(3, 1)',
'plt.LinearLocator(5)',
'plt.LogLocator(2, [1.0])',
'plt.AutoLocator()',
]

n_locators = len(locators)

size = 512, 40 * 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')

plt.subplots_adjust(bottom=.01, top=.99, left=.01, right=.99)
plt.show()

所有這些locators均來自於基類matplotlib.ticker.Locator。你可以通過繼承該基類創建屬於自己的locator樣式。同時matplotlib也提供了特殊的日期locator, 位於matplotlib.dates.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章