import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
# 定义Logistic模型函数
def logistic_model(t, r, K):
return K / (1 + np.exp(-r * (t - t0)))
# 准备数据
t_data = np.array([2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022])
y_data = np.array([810828, 845459, 879391, 909091, 927292, 935952, 939678, 945879, 972785, 993595, 1025308, 1078989, 1123270, 1164790, 1209140, 1247510, 1268250])
# 初始参数猜测值
r_guess = 0.01
K_guess = 1500000
p0 = [r_guess, K_guess]
# 使用curve_fit进行拟合
popt, pcov = curve_fit(logistic_model, t_data, y_data, p0=p0)
# 从popt中提取最佳拟合参数r和K,并赋予正确的名称
r_estimated, K_estimated = popt
# 打印最佳拟合参数
print(f"Estimated growth rate (r): {r_estimated:.4f}")
print(f"Estimated carrying capacity (K): {K_estimated}")
# 使用最佳拟合参数绘制拟合曲线
t_fit = np.linspace(min(t_data), max(t_data), 300) # 生成更细致的时间点
y_fit = logistic_model(t_fit, r_estimated, K_estimated) # 计算拟合的因变量值
# 绘制数据点和拟合曲线
plt.scatter(t_data, y_data, label='Data Points')
plt.plot(t_fit, y_fit, label=f'Fitted Logistic Curve (r={r_estimated:.4f}, K={K_estimated:.0f})')
plt.xlabel('Year')
plt.ylabel('Population')
plt.title('Logistic Growth Model Fit to Population Data')
plt.legend()
plt.show()
为什么画不出图啊