天天看點

使用matplotlib和numpy繪制拟合曲線

import matplotlib.pyplot as plt
import numpy as np
data_x = ['1995', '1996', '1997', '1998', '1999', '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009']
data_y = [0.32, 0.32, 0.32, 0.32, 0.33, 0.33, 0.34, 0.37, 0.37, 0.37, 0.37, 0.39, 0.41, 0.42, 0.44]

# 使用matplotlib繪制折線圖
data_x = np.array(data_x).astype(int)
for a,b in zip(data_x, data_y):
    plt.text(a,b,b, ha='center', va='bottom')
plt.scatter(data_x, data_y, marker='o')
# 繪制曲線
poly = np.polyfit(data_x, data_y, deg=2)
y_value = np.polyval(poly, data_x)
plt.plot(data_x, y_value)

plt.legend()
plt.show()
           
使用matplotlib和numpy繪制拟合曲線

這裡需要把x軸資料轉換為int數值型資料,不然會報錯,因為年份清單的元素都是字元串類型。

np.polyfit(data_x, data_y, deg=1)是直線

使用matplotlib和numpy繪制拟合曲線