2018年10月11日 星期四

matplotlib note

matplotlib note

簡單理解matplitlib layout

matplotlib 圖示

上圖是matplotlib中常用的幾個物件。Figurematplotlib.figure.Figure物件,可看做整個畫布;Axes是matplotlib.axes.Axes物件,實際上會把資料畫在Axes上頭。

簡單的繪圖是直接使用matplotlib.pyplot.plot()。此方法會隱式的建立一個Figure,將其設定為current Figure,在此Figure下隱式的建立一個matplotlib.axes._subplots.Axes(一種Axes),最後把數據繪製在該Axes上,並回傳Line物件。

這樣的方法使用上相當簡單,但由於FigureAxes物件都是被隱式的建立,當具有多個Axes與多個Figure時,需要使用plt.get_fignumsplt.gcfplt.gca等方法進行切換,管理上變得相當複雜。

稍微複雜,但可以明確觀察物件的方始是手動新增FigureAxes,並存成變數加以管理。實際的程式碼如下 :

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 100, 0.1)-50
y = x**3

fig = plt.figure()
axes = fig.add_axes((0.1, 0.1, 0.8, 0.8))
lines = axes.plot(x, y)
fig.show()

在上頭的範例中,add_axes函數的第一個參數是axes的(左邊界位置, 下邊界位置, 寬度, 高度),其單位是fig中長寬的比例。

藉由此方法,可以在單一程式中明確的建立多個Figure物件,並在單一Figure下建立多個Axes子圖。以下是簡單的範例:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 100, 0.1)-50
y = x**3

fig = plt.figure()
fig.add_axes((0.1, 0.1, 0.8, 0.8))
fig = plt.figure()
main_axes = fig.add_axes((0.1, 0.1, 0.8, 0.8))
main_lines = main_axes.plot(x, y)
sub_axes = fig.add_axes((0.2, 0.6, 0.15, 0.15))
main_lines = sub_axes.plot(x, y)

用物件的方式管理Figure執行起來明確得多。例如要刪除線段時,可以用line.remove(),學習上也較一般的方法明確得多。

沒有留言:

張貼留言