Matplotlib面向對象繪圖

Matplotlib中圖像的結構

atplotlib圖像中最重要的三個對象分別是figure(畫布),ax(座標系),axis (座標軸)。一個figure中可以有多個 ax(多個子圖),figure可以設置圖像的尺寸,背景色,像素等。一個ax中一般有多個 axis,如xaxisyaxisax可以設置子圖的大小,標題,數據的呈現形式,線型,顏色等。axis又有labeltick等對象,可以設置座標軸刻度,座標軸標籤,座標軸標題等。
在這裏插入圖片描述
在這裏插入圖片描述
面向對象繪圖一般自上而下:
0,繪圖前設置繪圖風格等全局參數,例如style,font等。

1,開始繪圖時,首先是figure對象佈局,包括大小size,像素dpi等。

2, 接着是axes對象規劃,包括圖形(如點線柱餅),axes區域(如背景顏色,柵格,圖例)等。

3,然後是axis對象設置,包括座標軸,刻度線,標籤等。

4,最後是添加文字信息,包括標題,數據標註,其他文字說明等。

0,繪圖前設置繪圖風格等全局參數,例如style,font等。
# 查看可用的繪圖風格
print(plt.style.available)

# 選擇繪圖風格
plt.style.use('bmh')

# 用來正常顯示中文標籤
plt.rcParams['font.sans-serif'] = ['FangSong'] # 指定默認字體
# 解決符號‘-’顯示爲方塊的問題
plt.rcParams['axes.unicode_minus'] = False

# 設置全局默認字體屬性
font = {'weight': 'bold', 'size': 15}
plt.rc('font', **font)
1,開始繪圖時,首先是figure對象佈局,包括大小figsize,像素dpi等。

參考

fig = plt.figure()
2,接着是axes對象規劃,包括圖形(如點線柱餅),axes區域(如背景顏色,柵格,圖例)等。
ax = fig.add_subplot(111, facecolor=(0, 1, 0, 0.3))
# ax.figure(dpi=600)
ax.plot(x, y,
        label='$sin(x)$',
        color='r',
        linestyle="-",
        linewidth=3,
        marker="o", markeredgecolor='g', markersize=8,
        markerfacecolor='red',
        alpha=0.8)
# 網格設置
ax.grid(color='b', linestyle=':', linewidth=1)
# 圖例設置
ax.legend(loc='best', fontsize=18, frameon=True)
plt.show()

3,然後是axis對象設置,包括座標軸,刻度線,標籤等。

# 座標軸的範圍
ax.axis([-0.5, 6.5, -1.1, 1.1])

# 設置刻度
ax.xaxis.set_ticks([0, np.pi / 2, np.pi, 3 * np.pi / 2, 2 * np.pi])
# 設置刻度標籤
ax.xaxis.set_ticklabels(['$0$', '$\\frac{\pi}{2}$',
                         '$\pi$', '$\\frac{3\pi}{2}$',
                         '$2\,\pi$'

                         ])
# ax.set_xticks()
# ax.set_xticklabels()
# ax.xaxis.set_major_locator()
# ax.xaxis.set_major_formatter()

# 設置座標軸標題
ax.set_xlabel('X ', fontsize=20)
ax.set_ylabel('Y ', fontsize=20, rotation=0)
# ax.xaxis.set_label_text('X',fontsize = 20)
# ax.yaxis.set_label_text('y',fontsize = 20,rotation =0)

# 設置座標軸。標籤的位置
ax.xaxis.set_label_coords(1,-0.05)
ax.yaxis.set_label_coords(-0.05,1)

# 設置座標軸是否可見
ax.spines['right'].set_visible(False)

#設置座標軸顏色,當顏色爲 none 時,座標軸不可見
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('red')

# 移動座標軸的位置
ax.spines['left'].set_position(("data",0))
ax.spines['bottom'].set_position(("data",0))

4,最後是添加文字信息,包括標題,數據標註,其他文字說明等。

# 設置標題
ax.set_title(u'正弦曲線',color='black',fontsize=20)

# ax.annotate(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
#          )
# ax.text(0.85,0.75,'matplotlib\n plot',fontsize=20,
#         horizontalalignment='center',
#         verticalalignment='center',
#         transform= ax.transAxes,
#         bbox=dict(facecolor='green',alpha=0.6))


fig.savefig(u'02020202.png',dpi=600)

其它方法;

formatter = ticker.FormatStrFormatter('$%1.2f')
ax.yaxis.set_major_formatter(formatter)

case 1

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

# Fixing random state for reproducibility
np.random.seed(19680801)

fig, ax = plt.subplots()
ax.plot(100*np.random.rand(20))

formatter = ticker.FormatStrFormatter('$%1.2f')
ax.yaxis.set_major_formatter(formatter)

for tick in ax.yaxis.get_major_ticks():
    tick.label1.set_visible(False)
    tick.label2.set_visible(True)
    tick.label2.set_color('green')
# ax.yaxis.get_major_ticks() 返回兩個縱軸的座標,label1,label2分別表示不同的軸

plt.show()
 

在這裏插入圖片描述

Formatters and Locators


'Axis.get_major_formatter'		Get the formatter of the major ticker
'Axis.get_major_locator'		Get the locator of the major ticker
'Axis.get_minor_formatter'		Get the formatter of the minor ticker
'Axis.get_minor_locator	'		Get the locator of the minor ticker
'Axis.set_major_formatter'		Set the formatter of the major ticker.
'Axis.set_major_locator	'		Set the locator of the major ticker.
'Axis.set_minor_formatter'		Set the formatter of the minor ticker.
'Axis.set_minor_locator'		Set the locator of the minor ticker.
from matplotlib.ticker import NullFormatter, FixedLocator
ax.grid(True)
ax.set_xlim([-180, 180])
ax.yaxis.set_minor_formatter(NullFormatter())
ax.yaxis.set_major_locator(FixedLocator(np.arange(-90, 90, 30)))

在這裏插入圖片描述
主、副刻度密度的設置

ax.xaxis.set_major_locator(MultipleLocator(20))  # 設置20倍數
ax.xaxis.set_major_formatter(FormatStrFormatter('%5.1f'))  # 設置文本格式

# y軸
ax.yaxis.set_major_locator(MultipleLocator(100))  # 設置100倍數
ax.yaxis.set_major_formatter(FormatStrFormatter('%1.2f'))  # 設置文本格式

# 設置軸的副刻度
# x軸
ax.xaxis.set_minor_locator(MultipleLocator(5))  # 設置10倍數
# ax.xaxis.set_minor_formatter(FormatStrFormatter('%2.1f'))  # 設置文本格式

# y軸
ax.yaxis.set_minor_locator(MultipleLocator(50))  # 設置50倍數
# ax.yaxis.set_minor_formatter(FormatStrFormatter('%1.0f'))  # 設置文本格式

Axis Label


'Axis.set_label_coords'		Set the coordinates of the label.
'Axis.set_label_position'	Set the label position (top or bottom)
'Axis.set_label_text'		Set the text value of the axis label.
'Axis.get_label_position'	Return the label position (top or bottom)
'Axis.get_label_text'		Get the text of the label

Ticks, tick labels and Offset text

'Axis.grid'					Configure the grid lines.
'Axis.set_tick_params'		Set appearance parameters for ticks, ticklabels, and gridlines.
'Axis.axis_date'			Sets up axis ticks and labels treating data along this axis as dates.

Discouraged

'Axis.set_ticklabels'	Set the text values of the tick labels.
'Axis.set_ticks'	Set the locations of the tick marks from sequence ticks

雙Y軸

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

ax2.tick_params(axis='y', labelcolor=color)
# 刻度和標籤設置

matplotlib.axes.Axes.tick_params

設置刻度線和刻度標籤的位置
matplotlib.axis.YAxis.set_ticks_position

axis.Axis.set_ticks()

設置刻度和標籤


Axis.set_ticks(self, ticks, minor=False)
		ticks : sequence of floats
		minor : bool
設置刻度和標籤
Axis.set_ticks_position(self, position)

設置刻度和標籤的位置

YAxis.set_ticks_position(self, position)

Parameters:	
position : {'left', 'right', 'both', 'default', 'none'}

如果時y軸的,可以設置參數爲上面的

# loc 表示位置,spine表示當前位置的對象
for loc, spine in ax.spines.items():
	   print(loc)
	   print(spine)

left
Spine
right
Spine
bottom
Spine
top
Spine
spines.Spine.set_position()

設置 X,Y,軸分離開:

1.spines.Spine.set_position
.set_position(self, position)

spine.set_position(('outward', 10))  # outward by 10 points

2. .set_color(self, c)

3. .set_smart_bounds(self, value)

Spine Placement Demo:

fig = plt.figure()
x = np.linspace(-np.pi, np.pi, 100)
y = 2 * np.sin(x)

ax = fig.add_subplot(2, 2, 1)
ax.set_title('centered spines')
ax.plot(x, y)
ax.spines['left'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('center')
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax = fig.add_subplot(2, 2, 2)
ax.set_title('zeroed spines')
ax.plot(x, y)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax = fig.add_subplot(2, 2, 3)
ax.set_title('spines at axes (0.6, 0.1)')
ax.plot(x, y)
ax.spines['left'].set_position(('axes', 0.6))
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position(('axes', 0.1))
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax = fig.add_subplot(2, 2, 4)
ax.set_title('spines at data (1, 2)')
ax.plot(x, y)
ax.spines['left'].set_position(('data', 1))
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position(('data', 2))
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

在這裏插入圖片描述
2.

import matplotlib.pyplot as plt
import numpy as np


def adjust_spines(ax,spines):
    for loc, spine in ax.spines.items():
        if loc in spines:
            spine.set_position(('outward', 10))  # outward by 10 points
        else:
            spine.set_color('none')  # don't draw spine

    # turn off ticks where there is no spine
    if 'left' in spines:
        ax.yaxis.set_ticks_position('left')
    else:
        # no yaxis ticks
        ax.yaxis.set_ticks([])

    if 'bottom' in spines:
        ax.xaxis.set_ticks_position('bottom')
    else:
        # no xaxis ticks
        ax.xaxis.set_ticks([])

fig = plt.figure()

x = np.linspace(0,2*np.pi,100)
y = 2*np.sin(x)

ax = fig.add_subplot(2,2,1)
ax.plot(x,y)
adjust_spines(ax,['left'])

ax = fig.add_subplot(2,2,2)
ax.plot(x,y)
adjust_spines(ax,[])

ax = fig.add_subplot(2,2,3)
ax.plot(x,y)
adjust_spines(ax,['left','bottom'])

ax = fig.add_subplot(2,2,4)
ax.plot(x,y)
adjust_spines(ax,['bottom'])

plt.show()

在這裏插入圖片描述


更多參考官方文檔:https://matplotlib.org/api/axis_api.html

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