gpt4 book ai didi

python - 如何(重新)缩放 x Axis 以适合图中的某些点?

转载 作者:太空宇宙 更新时间:2023-11-03 15:58:15 28 4
gpt4 key购买 nike

我想重新调整我的(定性)x Axis ,使两个峰值(图中可见)与其实际值相关(即 500 keV 和 1274 MeV)。我该怎么做?

import numpy as np
import matplotlib.pyplot as plt

def read_from_file(filename):
return np.loadtxt(filename)

data = list(read_from_file("calibration.txt"))

print(data.index(max(data[:2000])))#x value 500kev
print(data.index(max(data[2000:])))#x value 1274

fig = plt.figure()
ax = fig.add_subplot(111)
x = range(len(data))
plt.plot(x, data)
plt.xlim(0, 5000)
plt.ylim(0, 7000)
plt.title("$^{22}$Na Spectrum")
plt.xlabel("Energy")
plt.ylabel("Amount of Photons")
plt.grid()
ax.annotate("500 keV", xy = (1450, 6541), xytext = (1600, 6500))
ax.annotate("1274 MeV", xy = (3500, 950), xytext = (3700, 1100))
plt.show()

enter image description here

最佳答案

使用 numpy,您可以使用 argmax 找到两个尖峰的索引(即无需将数据转换为列表)。

然后,您可以使用以下方法缩放 x 值:

xnew = val1 + (x - max1) / (max2 - max1) * (val2 - val1)

val1val2 是峰值的值,max1max2 是指标那些山峰。

这里有一些应该可以工作的代码:

import numpy as np
import matplotlib.pyplot as plt

# Fake some data approximately in your range. You can ignore this bit!
# Random numbers for noise
data = 1000. + np.random.rand(5000) * 100.
x = np.arange(len(data))
# Add the first spike
mu1, sd1 = 1450., 300.
pdf1 = (1./(sd1*2.*np.pi) * np.exp(-(x - mu1)**2 / sd1**2)) * 1e7
data += pdf1
# Add the second spike
mu2, sd2 = 3500., 200.
pdf2 = (1./(sd2*2.*np.pi) * np.exp(-(x - mu2)**2 / sd2**2)) * 1e6
data += pdf2
# End of fake data generation

# Find the index of the first maximum (using your '2000' cutoff)
cutoff = 2000
max1 = float(np.argmax(data[:cutoff]))
# Find the index of the second cutoff
max2 = float(np.argmax(data[cutoff:]) + cutoff)

# The actual values of the two spikes
val1, val2 = 500., 1274

# Scale the xvalues
xnew = val1 + (x - max1) / (max2 - max1) * (val2 - val1)

# Plot
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(xnew, data)
ax.set_ylim(0, 7000)
ax.set_title("$^{22}$Na Spectrum")
ax.set_xlabel("Energy")
ax.set_ylabel("Number of Photons")
ax.grid()

# Add some lines at the actual spikes to check scaling worked
ax.axvline(val1)
ax.axvline(val2)

plt.show()

enter image description here

关于python - 如何(重新)缩放 x Axis 以适合图中的某些点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41984104/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com