【问题标题】:Plotting bestfit curve to histogram将最佳拟合曲线绘制到直方图
【发布时间】:2014-04-03 17:57:27
【问题描述】:

我花了一整天的时间尝试使用 curve_fit 和其他任何方法将简单的最佳拟合曲线绘制到直方图上,但我失败了。在我的束缚结束时,我求助于发布我的代码块,希望有人至少可以指出我绘制这条曲线的正确方向。我是一个完全的编程新手,所以请忽略任何糟糕的编码。这是我的代码:

  # Velocity Verlet integrator

def Verlet(x, V, dt, A):

    x_new = x + V*dt + (A(x,V,R)*(dt**2)/2)
    V_new =((2)/2+dt)*(V + ((dt/2)*(((48/x_new**13)-(24/x_new**7)) + ((g*2)**(0.5))*R + ((48/x**13)-(24/x**7)) - g*V + ((g*2)**(0.5))*R)))
    return (x_new, V_new)


# Start main program

# Import required libraries
import numpy as np
from numpy import array, zeros
import random   


mu, sigma = 0, 1 # mean and variance
S = np.random.normal(mu, sigma, 1000) # Gaussian distribution

g=10 #gamma damping factor


# Define the acceleration function

def A(x,V,R):

    Acc = (((48/x**13)-(24/x**7)) - g*V + ((g*2)**(0.5))*(R))

    return Acc

# Set starting values for position and velocity
x = array([3])
V = array([0])




N = 100000 # number of steps
M = 10 # save position every M_th step
dt = 0.01 # interval

# Lists for storing the position and velocity
Xlist = zeros([1,N/M]) #define vector dimensions
Vlist = zeros([1,N/M])

# Put the initial values into the lists
Xlist[:,0] = x
Vlist[:,0] = V

# Run simulation

print "Total number of steps:", N
print "Saving position and velocity every %d steps." % (M)
print "Start."
for i in range(N/M):
    # Run for M steps before saving values
    for j in range(M):
          # Update position and velocity based on the current ones
          # and the acceleration function 
          R = random.choice(S) # selects a different random number from S each time
          x, V = Verlet(x, V, dt, A) #calculates new pos and vel from Verlet algorithm

    # Save values into lists
    Xlist[:, i] = x
    Vlist[:, i] = V
print ("Stop.")




#Define the range of steps for plot
L = []

k=0
while k < (N/M):
    L.append(k)
    k = k + 1


#convert lists into vectors
Xvec = (np.asarray(Xlist)).T #Transpose vectors for plotting purpose
Vvec = (np.asarray(Vlist)).T


KB=1.3806488*(10**(-23)) #Boltzmann constant

AvVel = (sum(Vvec)/len(Vvec)) #computes average velocity
print "The average velocity is: ", AvVel


Temp = ((AvVel**2)/(3*KB)) #Temperature calculated from equipartition theorem
print "The temperature of the system is: ", Temp,


#################
##### plots #####
#################


# Plot results
from matplotlib import pyplot as plt


#plots 1-d positional trjectory vs timestep
plt.figure(0)
plt.plot(Xvec,L) 
# Draw x and y axis lines
plt.axhline(color="black")
plt.axvline(color="black")

plt.ylim(0, N/M)
plt.xlim(0,6) #set axis limits

plt.show()




#plots postion distribution histogram
plt.figure(1)
num_bins = 1000
# the histogram of the data
npos, binspos, patches = plt.hist(Xvec, num_bins, normed=1, facecolor='blue', edgecolor = "none", alpha=0.5)
PH = plt.hist(Xvec, num_bins, normed=1, facecolor='blue', edgecolor = "none", alpha=0.5)
plt.xlabel('Position')
plt.ylabel('Timestep')
plt.title(r'Position distribution histogram')

plt.show()

我得到的位置直方图是一个很好的倒立伦纳德-琼斯势。但是我想为此绘制一条曲线以获得此最佳拟合曲线的函数形式。我看到的所有示例都将曲线绘制到定义的函数上,这显然很简单,但是将曲线绘制到直方图的艺术似乎是一个隐藏的秘密。任何帮助是极大的赞赏。谢谢。

顺便说一句,这是我对尝试的完整猜测

from scipy.optimize import curve_fit

def func(x,a):
    return (-a(1/((x^12)-(x^6))))


p0 = [1., 0., 1.]

coeff, var_matrix = curve_fit(func, binspos, npos, p0=p0)

# Get the fitted curve
hist_fit = func(binspos, *coeff)

plt.plot(binspos, hist_fit, label='Fitted data')
plt.show()

【问题讨论】:

  • 你试过打电话给func(binspos, *p0)吗?
  • 我实际上无法正常工作,到处都是错误!哇,我真的没想到这种微不足道的事情会如此困难
  • 如果您在问题中发布错误消息,人们可能会为您提供帮助。
  • @silvado 对不起,我昨天沮丧地退出了,但你是对的,发布错误是正确的做法。我收到以下奇怪的错误:TypeError: ufunc 'bitwise_xor' not supported for the input types, and the input could not be safe to force to any supported types based on the cast rule ''safe''
  • Python 中的幂运算符是**,而不是^

标签: python plot histogram curve


【解决方案1】:

据我了解,您想将直方图绘制为曲线而不是条形吗?只需将hist 函数返回的数据binspos, nposplot 函数一起使用即可。问题是 bin 边缘比数据点多一个,因此您必须计算 bin 的中心:

bin_centers = binspos[:-1] + 0.5 * np.diff(binspos)

然后只绘制直方图数据:

plt.plot(bin_centers, npos)

如果你真的想在这里进行曲线拟合,你可能不得不使用bin_centers 作为 x 轴的输入数据,希望这样的事情会起作用:

coeff, var_matrix = curve_fit(func, bin_centers, npos, p0=p0)

【讨论】:

  • 是的,我可以像你说的那样绘制数据点,但我实际上是在平滑的最佳拟合曲线之后,而不是实际的绘图本身。我如何指示 Python 用我拥有的数据绘制这条最佳拟合曲线?感谢您的回复
【解决方案2】:

哦,多么尴尬!这是一个愚蠢的语法错误,这是有问题的代码,而不是 ^ 而不是 **。糟糕的。总之,感谢大家的意见和帮助!

def func(x,a):
    return (-a(1/((x^12)-(x^6))))

【讨论】:

  • 不要太沮丧,这种事情随着经验变得更容易!它仍然会发生,但不是恒定的!
  • 另外,您可能想检查它是否真的是您想要的 1/(x^12-x^6) 或更典型的 1/x^12-1/x^6分子中有不同的因素。你的第一个 python 代码是正确的, 48/x13-24/x7 是 -4*(1/x12-1/x6) 的导数.
猜你喜欢
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多