我的目标是使以下函数适合我的数据:
def P(t, CP, Pan, tau):
P_val = CP + Pan / (1 + t / tau)
P_val = np.where(t >= 900, P_val - 0.8 * np.log(t / 900), P_val)
return P_val
然后绘制此函数。但是,我想对t<900
和 的情况使用两种不同的颜色t>=900
。因此,我决定分别绘制曲线的两部分,如下所示。然而,即使我尝试明确地将 合并到用于绘制曲线两部分的时间数组中
,这仍然会导致两条曲线之间留有很小的空隙。有点像这样:t=900
如果强制包含t=900
,间隙问题可以解决,但其余问题就会崩溃,我得到两条绘制的曲线:
我应该如何解决这个问题?或者是否有其他解决方法/方法(例如,多色线条)可以得到具有两种不同颜色的连续曲线,我可以在这里使用吗?根据Matplotlib 文档,LineCollection
可能有用,但不幸的是,我不太习惯matplotlib.collections
。
这是我的完整代码:
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
# Data
t2 = np.array([
80,
160,
200,
320,
400,
640,
800,
900,
1000,
1280,
2000,
])
P_t2 = np.array([
4.64,
3.97,
3.79,
3.48,
3.36,
3.18,
3.11,
3.08,
3.06,
3.01,
2.94,
])
t_min = 0
t_cutoff = 7500
mask = (t2 >= t_min) & (t2 <= t_cutoff)
t_filtered = t2[mask]
P_t_filtered = P_t2[mask]
def P(t, CP, Pan, tau):
P_val = CP + Pan / (1 + t / tau)
P_val = np.where(t >= 900, P_val - 0.8 * np.log(t / 900), P_val)
return P_val
initial_guesses = [3.0, 4.0, 50.0]
bounds = ([1.35, 0, 0], [np.inf, np.inf, np.inf])
popt2, pcov2 = curve_fit(P, t_filtered, P_t_filtered, p0=initial_guesses, bounds=bounds, maxfev=5000)
t_fit2 = np.linspace(1, max(t2), 500)
P_fit2 = P(t_fit2, *popt2)
t_fit2_middle = t_fit2[(t_fit2 >= 80) & (t_fit2 <= 900)]
t_fit2_middle = np.append(t_fit2_middle, 900) # include 900 explicitly
t_fit2_over = t_fit2[t_fit2 >= 900]
#t_fit2_over = np.append(t_fit2_over, 900) # include 900 explicitly
P_fit2_middle = P(t_fit2_middle, *popt2)
P_fit2_over1 = P(t_fit2_over, *popt2)
#plotting
plt.plot(t_fit2_middle, P_fit2_middle, color='green', linewidth=2)
plt.plot(t_fit2_over, P_fit2_over1, color='red', linewidth=2)
plt.fill_between(t_fit2_middle, 0, P_fit2_middle, color='green', alpha=0.3, hatch='//')
plt.fill_between(t_fit2_over, P_fit2_over1, color='red', alpha=0.3, hatch='//')
plt.xlim(1, 1250)
plt.ylim(0, 8)
plt.minorticks_on()
ax = plt.gca()
ax.tick_params(labelbottom=False, labelleft=False)
plt.tight_layout()
plt.show()