【发布时间】:2020-12-29 04:03:00
【问题描述】:
我需要根据另一个文件中的一些数据绘制直方图。
目前我有绘制散点图并拟合高斯的代码。
x 值是它正在读取的数据文件中相应行上的任何数字(在其他信息的前 12 行之后,即第 13 行是第一个事件),y 值是数字行数乘以一个值。
然后绘制并拟合散点图,但我需要能够将其绘制为直方图,并且能够更改 bin 宽度/数量(即将 bin 1、2、3 和 4 加在一起以获得 1/4整个垃圾箱的事件数量是事件数量的 4 倍——所以我猜想将数据中的多行加在一起),这就是我卡住的地方。
我将如何将其放入直方图并调整宽度/数字?
下面的代码,不知道如何使它漂亮。让我知道是否可以使它更易于阅读。
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from numpy import exp, loadtxt, pi, sqrt, random, linspace
from lmfit import Model
import glob, os
## Define gaussian
def gaussian(x, amp, cen, wid):
"""1-d gaussian: gaussian(x, amp, cen, wid)"""
return (amp / (sqrt(2*pi) * wid)) * exp(-(x-cen)**2 / (2*wid**2))
## Define constants
stderrThreshold = 10
minimumAmplitude = 0.1
approxcen = 780
MaestroT = 53
## Define paramaters
amps = []; ampserr = []; ts = []
folderToAnalyze = baseFolder + fileToRun + '\\'
## Generate the time array
for n in range(0, numfiles):
## Load text file
x = np.linspace(0, 8191, 8192)
fullprefix = folderToAnalyze + prefix + str(n).zfill(3)
y = loadtxt(fullprefix + ".Spe", skiprows= 12, max_rows = 8192)
## Make figure
fig, ax = plt.subplots(figsize=(15,8))
fig.suptitle('Coincidence Detections', fontsize=20)
plt.xlabel('Bins', fontsize=14)
plt.ylabel('Counts', fontsize=14)
## Plot data
ax.plot(x, y, 'bo')
ax.set_xlim(600,1000)
## Fit data to Gaussian
gmodel = Model(gaussian)
result = gmodel.fit(y, x=x, amp=8, cen=approxcen, wid=1)
## Plot results and save figure
ax.plot(x, result.best_fit, 'r-', label='best fit')
ax.legend(loc='best')
texttoplot = result.fit_report()
ax.text(0.02, 0.5, texttoplot, transform=ax.transAxes)
plt.close()
fig.savefig(fullprefix + ".png", pad_inches='0.5')
当前输出:散点图,确实显示了数据的预期分布和图(但是它们确实有一个糟糕的减少 chi^2,但一次有一个问题)
预期输出:相同数据的直方图,具有相同的分布和拟合,当每个事件被绘制为单独的 bin 时,希望可以将这些 bin 添加在一起以减少误差线
错误:不适用
数据:它基本上是超过 8192 行的标准分布。 1 个文件的完整数据为 here。还有原始的.Spe 文件、分散的plot 和完整版的code
2020-11-23 更新来自答案评论:
-
您好,我已经尝试实施了一段时间,但没有解决问题。我试图密切关注您的示例,但是我得到的直方图仍然具有 1 的 bin 宽度(即不加在一起)。我还在打印输出中获得了第二个空白图表,并且报告仅在 IDE 中打印输出(尽管我正在研究那个,并且估计我很快就会拥有它)。同样出于某种原因,它似乎在循环的 50 次迭代中的 3 次后停止。
-
这是当前状态下的code:
-
这是我得到的输出:
-
以防万一它有用,这是raw data。我似乎无法复制您的最后 2 个数字
-
理想的情况是能够将第 30 行的常数更改为所需的 bin 宽度,并在该情况下以该 bin 宽度运行。
【问题讨论】:
标签: python matplotlib plot histogram scatter-plot