python plotting覆盖数据

时间:2013-06-29 03:17:20

标签: python matplotlib

我在一个文件夹中有很多二进制文件和ascii文件。我正在使用glob模块阅读它们。处理二进制数据,以便我可以绘制它们。最后,我试图在一个子图中绘制简化的二进制数据,在另一个子图中绘制正常的ascii文件。我面临的问题是它可以生成相应二进制文件的图。但对于ascii文件,它只是简单地覆盖以前的文件,并始终生成相同的图。以下是示例代码的简化版本 -

import glob 
import numpy as np
from struct import unpack
import matplotlib.pyplot as plt

chi = sorted(glob.glob('C:/Users/Desktop/bin/*.chi'))

for index,fh in enumerate(chi):
    data = np.genfromtxt(fh, dtype = float)
    x = [row[0] for row in data]
    y = [row[1] for row in data]

binary = sorted(glob.glob('C:/Users/Desktop/bin/*.bin'))

for count,FILE in enumerate(binary):
    F = open(FILE,'rb')
    B = unpack('f'*1023183, F.read(4*1023183))
    A = np.array(B).reshape(1043, 981)
    F.close()

    #a = something column 1   # some further processing
    #b =  something column 2  # and generates 1D data

    fig = plt.figure(figsize=(11, 8.0))

    ax1 =fig.add_subplot(211,axisbg='w')
    ax1.plot(a,b)

    ax2 =fig.add_subplot(212, axisbg ='w')
    ax2.plot(x,y)

    plt.show()

有人可以解释为什么文件只在一组数据的绘图过程中相互替换,而另一组正在密谋绘制?

1 个答案:

答案 0 :(得分:1)

在您的示例中,循环的结构不正确,您必须在ascii文件的循环内部使用plot命令,否则只绘制最后一个。这应该有效:

尝试这样:

import glob 
import numpy as np
from struct import unpack
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(11, 8.0))

chi = sorted(glob.glob('C:/Users/Desktop/bin/*.chi'))

for index,fh in enumerate(chi):
    data = np.genfromtxt(fh, dtype = float)
    x = [row[0] for row in data]
    y = [row[1] for row in data]

    ax1 =fig.add_subplot(211, axisbg ='w')
    ax1.plot(x,y)


binary = sorted(glob.glob('C:/Users/Desktop/bin/*.bin'))

for count,FILE in enumerate(binary):
    F = open(FILE,'rb')
    B = unpack('f'*1023183, F.read(4*1023183))
    A = np.array(B).reshape(1043, 981)
    F.close()

    #a = something column 1   # some further processing
    #b =  something column 2  # and generates 1D data


    ax2 =fig.add_subplot(212,axisbg='w')
    ax2.plot(a,b)

plt.show()