【问题标题】:Separate curve below fitting parameter拟合参数下方的单独曲线
【发布时间】:2021-12-18 17:38:32
【问题描述】:

我正在尝试在 python 中拟合我的曲线。

举个简单的例子,我能适应。

但是,我想在拟合参数值以下分离一条具有不同颜色或形状的曲线。

#This is my x  and y array

from numpy import sqrt
import pandas as pd
from scipy.optimize import curve_fit
from matplotlib import pyplot
import numpy as np
import csv


x = [2, 1.95, 1.9, 1.85, 1.8, 1.75, 1.7, 1.65, 1.6, 1.55, 1.5, 1.45, 1.4, 1.35
 1.3, 1.25, 1.2, 1.15, 1.1, 1.05, 1.01]
y = [1, 1, 1, 1, 0.99, 0.938, 0.9, 0.857, 0.762, 0.686, 0.59, 0.529, 0.509, 0.47, 0.462, 0.452, 0.452, 0.452, 0.457, 0.43,0.424]


print(len(x))
print(len(y))

def func(x, m, n):
    return  1 - 1/2 * np.exp(-(x - m)/(n))


params, covs = curve_fit(func, x, y)
 
print("params: ", params)
print("covariance: ", covs) 

for idx, value in enumerate(x):
    params, _ = curve_fit(func, x, y)
    m, n = params[0], params[1]
    if value >= m:
        yfit1 =  1 - 1/2 * np.exp(-(x - m)/(n))
    else:
        #params, _ = curve_fit(func, x, y)
        #r_t, n = params[0], params[1]
        yfit2 =  1 - 1/2 * np.exp(-(x - m)/(n))
    print(value)
    
plt.plot(x, y, 'bo', linestyle ='solid', marker=">", label="original")
plt.plot(x, yfit1,label="m >= %.3f"%m)
plt.plot(x, yfit2,'ko', marker='>', label="x < m")
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc='best', fancybox=True, shadow=True)
plt.grid(False)
plt.show() 

输出

params:  [1.19707919 0.52674861]

# So this gives 1.197 for m.

当我看到我的 x 数组时,我有几个值小于 m 的值(m=1.197 from params)。

所以我想以不同的方式绘制它们(颜色或大小),这样我就可以有两条不同的风格曲线,所有 x 都大于 m,其余 x 小于 m。

我试图通过创建两个方程来给出循环,但我无法得到任何区别。似乎在拟合线上绘制了相同的图表。

我能得到一些帮助吗? 任何帮助将不胜感激。

谢谢。

【问题讨论】:

    标签: python python-3.x python-2.7 scikit-learn curve-fitting


    【解决方案1】:

    你的 if-else 现在并没有真正起作用,因为无论 if 条件是真还是假,你都在做同样的事情。

    如果您有兴趣在不同的 x 间隔内使用不同的样式进行绘图,这里有一种方法(您只需替换代码的最终绘图部分):

    # Arrays offer an easier indexing compared to lists
    x = np.array(x)
    y = np.array(y) 
    
    plt.plot(x, y, 'bo', linestyle ='solid', marker=">", label="original")
    # Notice the different subsets of the arrays that are being plotted (x<=m and x>m) and tweak these as you like
    plt.plot(x[x<=m], yfit1[x<=m],label="m >= %.3f"%m)
    plt.plot(x[x>m], yfit1[x>m], 'r:', label="m >= %.3f"%m) 
    plt.plot(x, yfit2,'ko', marker='>', label="x < m")
    plt.xlabel('x')
    plt.ylabel('y')
    plt.legend(loc='best', fancybox=True, shadow=True)
    plt.grid(False)
    plt.show()
    

    【讨论】:

    • 感谢您的回复,您是对的,if 和 else 什么都不做。我正在尝试修复它。现在你的想法对我有用。非常感谢
    • 您好 Prahken 和 Dharman,是否有可能修改小于 m 值的曲线?实际上,我想在 m 小于 m 时显示一条 0.5 左右(在 y 轴上)的线,拟合曲线(对于 m 大于 x)在 0.5 之后开始。
    • 如果我理解正确,您只需要在 x>m 上评估您的拟合函数并为 x
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 2016-02-12
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 2021-06-17
    • 2015-11-15
    相关资源
    最近更新 更多