【问题标题】:How to make a logarithmic best fit line?如何制作对数最佳拟合线?
【发布时间】:2019-04-09 11:35:53
【问题描述】:

这是我现在拥有的代码,我有一些数据,我希望保留不确定性条。我需要的scipy 是什么?

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import statistics
from statistics import stdev


y1 = [73.64, 76.47, 75.70, 71.71, 73.70, 79.39]
y2 = [219.70, 206.96, 235.31, 189.91, 256.48, 210.25]
y3 = [241.11, 271.70, 255.19, 229.67, 222.30, 200.70]
y4 = [256.59, 263.97, 262.17, 243.14, 245.42, 256.55]

y1_mean = statistics.mean(y1)
y2_mean = statistics.mean(y2)
y3_mean = statistics.mean(y3)
y4_mean = statistics.mean(y4)

y = np.array([y1_mean, y2_mean, y3_mean, y4_mean])
x = np.array([0,0.3,1.5,3])
e = np.array([stdev(y1), stdev(y2), stdev(y3), stdev(y4)])


plt.errorbar(x, y, e, linestyle = 'none', color = 'turquoise' )

plt.scatter(x, y, color = 'green')

plt.xlabel('x-coordinates')
plt.ylabel('y-coordinates')
plt.title('Sample graph')
plt.show()

我希望它是这样的,但适合我的数据:

【问题讨论】:

  • 根据 log(x) a, b = np.polyfit(np.log(x), y, 1) 拟合 y,并绘制它 plt.plot(x, b+a*np.log(x))
  • 请同时显示您的所有导入,以便于复制和粘贴代码。
  • 已更新,因此可以根据要求更轻松地@Cleb

标签: python numpy matplotlib scipy curve-fitting


【解决方案1】:

由于解释不佳,不太确定您想要什么,但我会尝试通过使用 plt.semilogy() 和曲线拟合来帮助您。你可以试试plt.semilogy(x,y) 看看你得到了什么,但在这个解决方案中我想拟合曲线,所以这里是编辑后的代码,希望它能帮助你或指导你解决问题:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import statistics as st
import scipy as sp
from scipy.optimize import curve_fit

y1 = [6,5,6,7,8]
y2 = [8,9,10,10,11]
y3 = [14,15,16,14,14]
y4 = [16,17,18,19,18]

y1_mean = statistics.mean(y1)
y2_mean = statistics.mean(y2)
y3_mean = statistics.mean(y3)
y4_mean = statistics.mean(y4)

y = np.array([y1_mean, y2_mean, y3_mean, y4_mean])
x = np.array([3,5,6,8])
e = np.array([st.stdev(y1), st.stdev(y2), st.stdev(y3), st.stdev(y4)])


def f(x,a,b,c): 
        return a*(np.square(x))+(b*x)+c

popt, pcov = curve_fit(f, x, y)

fitA = popt[0]
fitB = popt[1]
fitC = popt[0]

yFit = f(x,fitA,fitB,fitC)


plt.errorbar(x, y, e, linestyle = 'none', color = 'k', label="Points" )
plt.semilogy(x,y, color='g', linestyle="--", label="Log")
plt.semilogy(x,yFit,color='r', label="Log Fit")
plt.scatter(x, y, color = 'k')
plt.xlabel('x-coordinates')
plt.ylabel('y-coordinates')
plt.title('Sample graph')
plt.legend()
plt.show()

这就是我得到的

【讨论】:

  • 我想要的是更多的曲线而不是带有锋利边缘的线条,我很抱歉我的措辞不佳,我是编程领域的新手。
  • 我更新了编码部分,使其更易于可视化
  • 这看起来像多项式拟合曲线,你试过吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 2014-09-07
  • 2013-08-24
相关资源
最近更新 更多