如何在单个文本文件中使用循环多个事件?

时间:2018-04-19 13:37:47

标签: python plot

我是编程的新手。我在单个文本文件(data.txt)中有多个事件(超过1000个事件数)。例如

BoardID: 31

Channel: 1

Event Number: 3123

Pattern: 0x0000

2627.000000

2627.000000

2626.009033

2629.000000
.
.
.(up to 1024 data)

BoardID: 31

Channel: 1

Event Number: 3124

Pattern: 0x0000

2627.000000

2627.000000

2628.949707

2626.099365
.
.
....(up to 1024 data)
.
..1000 number of events

如何通过在多个事件上使用循环逐个绘制所有数据。

我正在尝试以下python代码,但它不起作用:

with open("data.txt") as f:

for i in range(1000):  #I have 1000 number of events
    all_lines = f.readlines()
    def plot_event(start = 4, all_lines= 'all_lines'):
        lines = all_lines[start : 1029 - 4 + start]

        return (plot_event(4*i, all_lines))

    x = np.array(range(1,1025)) #for all the events x has same range
    y2 = float(lines.split()[0])
    y2_=list(y2)
    y22 = [((j / 4096)-0.5) for j in y2_]

fig = plt.figure()
ax = fig.add_subplot(111)   
ax.set_xlabel('Time (ns)')
ax.set_ylabel('counts')
ax.plot(x,y22, 'k-', color= 'b', label='data') 
fig=plt.gcf()
plt.show()
plt.draw()

有人可以解释我如何使用循环逐个绘制每个事件?

1 个答案:

答案 0 :(得分:0)

您拥有大部分正确的代码,只是缩进和排序的一些问题

你尝试读取1000x整个文件,除非你第一次到达文件的末尾并且什么都没有回来

此外,绘图应该在循环中

# read in the file. We only need to do this once
with open('data.txt') as f:
    all_lines = [line for line in f]

define x outside of the loop. Numpy has a range generating function. Use that
x = np.arange(1,1025)

# loop through each event
for start in range(1000):
    # get data points
    # each event has values at 1028*start:1028*(start+1), but we don't need the first 4 values
    # defining y2 as an array automatically handles the float conversion
    # also makes the math easier
    y2 = np.array(all_lines[1028*start+4:1028*(start+1)],dtype=float)
    y22 = y2 / 4096 - .5

    # plot stuff. I just copies your code here
    # only change was putting it in the loop
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlabel('Time (ns)')
    ax.set_ylabel('counts')
    ax.plot(x,y22, 'k-', color='b', label='data')
    fig = plt.gcf()
    plt.show()
    plt.draw()