天天看點

matplotlib1. --- 幾個畫圖之前的核心點Axes, Figure,Axis

作圖環境:vscode+插件Jupyter

matplotlib1. --- 幾個畫圖之前的核心點Axes, Figure,Axis

這段話很重要:

一個作圖的視窗就是一個Figure, 在Figure上可以有很多個Axes/Subplot,每一個Axes/Subplot為一個單獨的繪圖區,可以在上面繪圖,其中每一個Axes/subplot, 有XAxis,YAxis,在上面可以标出刻度,刻度的位置,以及xy軸的标簽label。

下圖為一個Figure上更詳細的内容:

matplotlib1. --- 幾個畫圖之前的核心點Axes, Figure,Axis
  1. 建立Figure

    plt.figure

    https://matplotlib.org/api/_as_gen/matplotlib.pyplot.figure.html

  • 常用的一個參數: figsize=(width, height), 可以指定(w,h),也可以用figaspect(ratio)計算。建立指定寬度和高度的Figure
  • Return : 傳回的是一個Figure窗體對象

函數:figaspect(ratio) https://matplotlib.org/api/_as_gen/matplotlib.figure.figaspect.html?highlight=figaspect#matplotlib.figure.figaspect

rcParams["figure.figsize"]

,取出height,并利用 r a t i o = h e u g h t w i d t h ratio = \frac{heught}{width} ratio=widthheught​計算出width,傳回(width, height)

import matplotlib.pyplot as plt
fig = plt.figure(figsize=plt.figaspect(2.0)) # an empty figure with no axes
fig.suptitle("No axec on this figure")  # Add a title so we know which it is


           
matplotlib1. --- 幾個畫圖之前的核心點Axes, Figure,Axis
  1. 在Figure上建立Axes

    所有的畫圖工作都在Axes上執行,一個Figure可以有很多個Axes,但是一個Axes隻能屬于一個Figure.

一般來說,你會建立一個Figure,然後再将Axes添加到Figure上。

你可能會使用

fig.add_axes

,但是,更多的時候使用

fig.add_subplot

更友善。

add_subplot(*args, **kwargs)

https://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html?highlight=add_subplot#matplotlib.figure.Figure.add_subplot

  • return : Axes執行個體
# 調用執行個體
add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
           
fig = plt.figure()
ax = fig.add_subplot(111) # We'll explain the "111" later. Basically, 1 row and 1 column.
ax.set(xlim=[0.5, 4.5], ylim=[-2, 8], title='An Example Axes',
       ylabel='Y-Axis', xlabel='X-Axis')
           
matplotlib1. --- 幾個畫圖之前的核心點Axes, Figure,Axis

以上代碼使用set設定了axes的很多屬性值,當然可以通過

set_*

來設定特定屬性的值,比如:

fig = plt.figure()
ax = fig.add_subplot(111) # We'll explain the "111" later. Basically, 1 row and 1 column.
ax.set_xlim([0.5, 4.5])
ax.set_ylim([-2, 8])
ax.set_title('A Different Example Axes Title')
ax.set_ylabel('Y-Axis (changed)')
ax.set_xlabel('X-Axis (changed)')
plt.show()
           
matplotlib1. --- 幾個畫圖之前的核心點Axes, Figure,Axis

基本的畫圖函數

大多數的畫圖工作都在Axes上,接下來會讨論更多的繪圖函數,在這主要介紹兩種最基本的方法:

plot

scatter

plot

主要将獨立的點用各種形式的線連起來,

scatter

畫出不同的點,并根據不同的值将點畫成不同大小會不同顔色。

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 2, 3, 4], [10, 20, 25, 30], color='lightblue', linewidth=3)
ax.scatter([0.3, 3.8, 1.2, 2.5], [11, 25, 9, 26], c=[1, 2, 3, 5], marker='^')
ax.set_xlim(0, 4.5)
plt.show()
           
matplotlib1. --- 幾個畫圖之前的核心點Axes, Figure,Axis

畫圖函數調用方法 Axes or pyplot

Axes 對象的任何一種方法,都在pyplot子產品中存在對象的方法,比如,

plt.xlim(1, 10)

pyplot講會調用

ax.set_xlim(1, 10)

其中,

ax

是目前環境下建立的Axes,比如:

fig = plt.figure()

# 建立Axes ax1
ax1 = fig.add_subplot(121)
# 此時調用的是ax1.plot
plt.plot([1, 2, 3, 4], [10, 20, 25, 30], color='lightblue', linewidth=3)

# 建立Axes ax2
ax2 = fig.add_subplot(122)
# 此時調用的ax2.scatter
plt.scatter([0.3, 3.8, 1.2, 2.5], [11, 25, 9, 26], c=[1, 2, 3, 5], marker='^')

plt.show()
           
matplotlib1. --- 幾個畫圖之前的核心點Axes, Figure,Axis

上述使用Axes的等效代碼:

plt.plot([1, 2, 3, 4], [10, 20, 25, 30], color='lightblue', linewidth=3)
plt.scatter([0.3, 3.8, 1.2, 2.5], [11, 25, 9, 26], c=[1, 2, 3, 5], marker='^')
plt.xlim(0.5, 4.5)
plt.show()
           

在以後的代碼中,基本使用Axes方法,雖然麻煩一點,但是代碼表達的意思很準确,不會産生歧義。

多個Axes

plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None)

https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots.html?highlight=pyplot%20subplots#matplotlib.pyplot.subplots

建立含有nrows行ncols列個Axes的Figure, 傳回(Figure, axes)

fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0,0].set(title='Upper Left')
axes[0,1].set(title='Upper Right')
axes[1,0].set(title='Lower Left')
axes[1,1].set(title='Lower Right')

# To iterate over all items in a multidimensional numpy array, use the `flat` attribute
for ax in axes.flat: # 将Axes平鋪為1維數組
    # Remove all xticks and yticks...
    ax.set(xticks=[], yticks=[])
    
plt.show()
           
matplotlib1. --- 幾個畫圖之前的核心點Axes, Figure,Axis

plt.subplots

的預設參數為

nrows=1, ncols=1

是以當不傳入參數調用

plt.subplots()

是也會建立單個Axes

是以:

fig = plt.figure()

ax = fig.add_subplot(111)

可以使用

fig, ax = plt.subplots()

代替

練習:

在代碼中填寫相應代碼段來建立以下圖像

matplotlib1. --- 幾個畫圖之前的核心點Axes, Figure,Axis
import numpy as np
import matplotlib.pyplot as plt


# Our data...
x = np.linspace(0, 10, 100)
y1, y2, y3 = np.cos(x), np.cos(x + 1), np.cos(x + 2)
names = ['Signal 1', 'Signal 2', 'Signal 3']

# add codes here
           

個人實作:

#%%
import numpy as np
import matplotlib.pyplot as plt

# Try to reproduce the figure shown in images/exercise_1-1.png

# Our data...
x = np.linspace(0, 10, 100)
y1, y2, y3 = np.cos(x), np.cos(x + 1), np.cos(x + 2)
names = ['Signal 1', 'Signal 2', 'Signal 3']
# add codes here
ys = [y1, y2, y3]
fig, axs = plt.subplots(nrows=3, ncols=1)
 
for index, ax in enumerate(axs):
    ax.plot(x, ys[index])
    ax.set_title(names[index])
    ax.set(xticks=[], yticks=[])

# 調整布局,顯示不重疊
fig.tight_layout()
plt.show()
           

繼續閱讀