Python 绘制直方图的最佳拟合曲线

Python 绘制直方图的最佳拟合曲线,python,plot,histogram,curve,Python,Plot,Histogram,Curve,我花了一整天的时间试图用曲线拟合和其他任何东西把一条简单的最佳拟合曲线绘制成直方图,但我失败了。在我穷途末路的时候,我求助于发布我的一堆代码,希望有人至少能为我指明绘制这条曲线的正确方向。我是一个完全的编程新手,所以请忽略任何糟糕的编码。这是我的密码: # 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)

我花了一整天的时间试图用曲线拟合和其他任何东西把一条简单的最佳拟合曲线绘制成直方图,但我失败了。在我穷途末路的时候,我求助于发布我的一堆代码,希望有人至少能为我指明绘制这条曲线的正确方向。我是一个完全的编程新手,所以请忽略任何糟糕的编码。这是我的密码:

  # 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()

据我所知,你想把柱状图绘制成曲线而不是条形图吗?只需将
hist
函数返回的数据
binspos、npos
plot
函数一起使用即可。问题是,数据点比数据点多出一个箱子边缘,因此您必须计算箱子的中心:

bin_centers = binspos[:-1] + 0.5 * np.diff(binspos)
然后绘制直方图数据:

plt.plot(bin_centers, npos)
如果您真的想在这里进行曲线拟合,您可能必须使用
bin_中心
作为x轴的输入数据,希望类似的东西可以工作:

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

哦,真尴尬!这是一个愚蠢的语法错误,下面是令人不快的代码,不是“^”而不是**。可怕的。无论如何,感谢大家的投入和帮助

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

是的,我可以像你说的那样画数据点,但我实际上是在画平滑的最佳拟合曲线,而不是实际的曲线本身。如何指示Python使用我拥有的数据绘制此最佳拟合曲线?感谢您的回复您是否尝试过拨打
func(binspos,*p0)
?事实上,我无法做到这一点,到处都是错误!哇,我真的没想到这么琐碎的事情会如此困难。如果你在问题中发布错误消息,人们可能会帮助你。@silvado很抱歉,我昨天因为沮丧而辞职,但你是对的,发布错误是正确的做法。我得到了以下奇怪的错误:TypeError:ufunc'bitwise\u xor'不支持输入类型,并且根据强制转换规则“safe”,输入不能安全地强制到任何支持的类型Python中的power操作符是
**
,而不是
^
。不要太沮丧,这类事情会随着经验变得更容易!它仍然会发生,但它不是常数!此外,您可能需要检查它是否真的是您想要的1/(x^12-x^6)或更典型的1/x^12-1/x^6,可能在分子中有不同的因子。您的第一个python代码就是这样正确的,48/x13-24/x7是-4*(1/x12-1/x6)的派生。
def func(x,a):
    return (-a(1/((x^12)-(x^6))))