2019年1月17日 星期四

[python] 最簡單的範例取得 figure 上的 ax list, 讓我們可以不斷的追加繪製圖形上去

關鍵:
list_ax = fig.get_axes() # 回傳 axes list 以供之後要追加畫圖使用



'''
Usage:
   data1 = [...]
   data2 = [...]
   data_mxn = [data1, data2]
   title_mxn = ['data1', data2']


   # 第一次 在 fig 1 上繪製訊號
   fig1 = plt.figure(figsize=(FIG_X_inch, FIG_Y_inch))
   list_ax = draw_line_mxn(fig1, data_mxn, title_mxn)  


   # 第二次 在 fig 1 上 位於  (1, 1) 的 ax 上, 再標記東西 (追加繪製)
   _, array_loc = dict_ecg_feature['r_loc']
   draw_loc(data_ecg, array_loc, '*', 5 , 'r', 'r_loc', list_ax[0])
'''


def draw_line_mxn(fig, data_nxm, title_nxm, color='blue'):
   row = len(data_nxm)
   
   y = 0
   for data in data_nxm:
       ax1 = fig.add_subplot(row, 1, y+1) # 建立 axes on fig
       draw_line(data, ax1, title_nxm[y], color) # 在 axes 上畫圖
       y = y + 1


   list_ax = fig.get_axes() # 回傳 axes list 以供之後要追加畫圖使用
   return list_ax

def draw_line(data, ax, title=None, color='black'):
   N = len(data)
   t = np.linspace(0, N, N)
   ax.plot(t, data, color)
   if title != None:
       ax.set_title(title)


def draw_loc(data, loc_array, mark_style, mark_size, mark_color, label, ax):
   data_array = np.asarray(data)
   ax.plot(loc_array, data_array[loc_array.astype(int)], mark_style, color = mark_color, markersize=mark_size, label=label)

   ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)