用途:給定折斷點坐標信息适秩,插值出折線圖上對應點的y值
例如:
輸入: cut_dots=np.array([[0,0.5],[8,0.65],[18,0.996],[63,0.996]]) #need min/max
輸出: 0.5 0.519 0.538 0.556 0.575 0.594 0.612 0.631 0.65 0.685 0.719 0.754 0.788 0.823 0.858 0.892 0.927 0.961 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996
完整代碼
import numpy as np
import matplotlib.pyplot as plt
def write2txt(txt_path,write_array,type):
with open(txt_path,'w') as f:
for i in range(write_array.size):
if type=='float':
print(np.around(write_array[i],3),end=' ',file=f)
print(np.around(write_array[i],3),end=' ')
elif type=='int':
print(write_array[i].astype(int),end=' ',file=f)
print(write_array[i].astype(int),end=' ')
def line_mode(cut_dots):
cut_dots_T = cut_dots.T
x = cut_dots_T[0]
y = cut_dots_T[1]
table_x = np.linspace(x[0],x[-1],x[-1]-x[0]+1)
for i in range(x.size-1):
if i==0:
table_y = np.linspace(y[0],y[1],x[1]-x[0]+1)
else:
table_y = np.concatenate((table_y, np.linspace(y[i],y[i+1],x[i+1]-x[i]+1)[1:]))
plt.plot(table_x, table_y)
plt.show()
return(table_x,table_y)
if __name__ == '__main__':
# 1. 定義折點澎迎,須包括第一個和最后一個點(務必確保最小和最大的x值)送爸,定義輸出值類型
cut_dots=np.array([[0,0.5],[8,0.65],[18,0.996],[63,0.996]]) #need min/max
type = 'float'#'int'
# 2. 繪制多段折線圖,并返回擬合的y值
table_x,table_y = line_mode(cut_dots)
# 3. 輸出&輸出為txt顷编,指定輸出文件名
txt = r'table_y.txt'
write2txt(txt,table_y,type)