最佳拟合线的直方图线呈锯齿状且不平滑?

Histogram line of best fit line is jagged and not smooth?

我似乎不太明白如何让我的曲线平滑显示而不是有那么多急转弯。 我希望展示玻尔兹曼概率分布。曲线优美。

我希望这是一个简单的修复,但我看不到。有人可以帮忙吗?

我的代码如下:

from matplotlib import pyplot as plt
import numpy as np
import scipy.stats
dE = 1
N = 500
n = 10000
# This is creating an array filled with all twos
def Create_Array(N):
    Particle_State_List_set = np.ones(N, dtype = int)
    Particle_State_List_twos = Particle_State_List_set + 1
    return(Particle_State_List_twos)
Array = Create_Array(N)
def Select_Random_index(N):
    Seed = np.random.default_rng()
    Partcle_Index = Seed.integers(low=0, high= N - 1)
    return(Partcle_Index)
def Exchange(N):
    Particle_Index_A = Select_Random_index(N) #Selects a particle to be used as particle "a"
    Particle_Index_B = Select_Random_index(N) #Selects a particle to be used as particle "b"
    
    # Checks to see if the energy on particle "a" is zero, if so it selects anbother until it isn't. 
    while Array[Particle_Index_A] == 1:
        Particle_Index_A = Select_Random_index(N)
        
     #This loop is making sure that Particle "a" and "b" aren't the same particle, it chooses again until the are diffrent.
    while Particle_Index_B == Particle_Index_A:
        Particle_Index_B = Select_Random_index(N)
        
    # This assignes variables to the chosen particle's energy values
    a = Array[Particle_Index_A]
    b = Array[Particle_Index_B]
    
    # This updates the values of the Energy levels of the interacting particles
    Array[Particle_Index_A] = a - dE  
    Array[Particle_Index_B] = b + dE
   
    return (Array[Particle_Index_A], Array[Particle_Index_B])
for i in range(n):
    Exchange(N)
# This part is making the histogram the curve will be made from
_, bins, _ = plt.hist(Array, 12, density=1, alpha=0.15, color="g")

# This is using scipy to find the mean and standard deviation in order to plot the curve
mean, std = scipy.stats.norm.fit(Array)

# This part is drawing the best fit line, using the established bins value and the std and mean from before
best_fit = scipy.stats.norm.pdf(bins, mean, std)

# Plotting the best fit curve
plt.plot(bins, best_fit, color="r", linewidth=2.5)

#These are instructions on how python with show the graph
plt.title("Boltzmann Probablitly Curve")
plt.xlabel("Energy Value")
plt.ylabel('Percentage at this Energy Value')
plt.tick_params(top=True, right=True)
plt.tick_params(direction='in', length=6, width=1, colors='0')
plt.grid()
plt.show()

发生的事情是在这些行中:

best_fit = scipy.stats.norm.pdf(bins, mean, std)
plt.plot(bins, best_fit, color="r", linewidth=2.5)

'bins' 直方图 bin 边缘被用作形成最佳拟合线的数据点的 x 坐标。生成的图是参差不齐的,因为它们之间的距离太远了。相反,您可以定义一组更紧凑的 x 坐标并使用它:

bfX = np.arange(bins[0],bins[-1],.05)
best_fit = scipy.stats.norm.pdf(bfX, mean, std)
plt.plot(bfX, best_fit, color="r", linewidth=2.5)

对我来说,这给出了一个很好的平滑曲线,但如果您不喜欢,您总是可以使用比 .05 更紧的包装。