jeudi 5 novembre 2015

Plot a different subplot depending on input files by only entering one parameter

I am trying to write a python script that gives me a different plot, depending on which input files I choose.

The background: I am doing research on acoustics and I have my data saved to one .hd5-file per sample. A plot consists of 6 subplots for one of my test series and 8 for the other one, all coming from different files. The plots itself are basically amplitudes in the same frequency range for each plot.

My question: How do I avoid having to switch the cases for L and LE manually by saying one is True and the other one False? Ideally I want to only enter "L" or "LE" somewhere. The filenames are actually more complex than the ones in the example below and I have to enter them manually, because they do have very similar names.

Here's a (hopefully) minimal example of what my file looks like now:

import h5py
import matplotlib.pyplot as plt

def savefig(filename):
    plt.savefig('{}.pdf'.format(filename))

# I have to enable one and disable the other, tedious!
L = True    # one test series
LE = False  # the other test series

# excluding the other case to prevent both being enabled
if L and not LE:
    files = ["1.h5", "2.h5", ....., "8.h5"]  # 8 files

if LE and not L:
    files = ["a.h5", "b.h5", ....., "f.h5"]  # 6 files

N = len(files)
ncols = 2  
nrows = int(len(files) / 2)

if L and not LE:
    fig, axes = plt.subplots(nrows, ncols)

if LE and not L:
    fig, axes = plt.subplots(nrows, ncols)

# here follows reading data from the .h5 file and plotting, just for sake of completeness. 
# Probably not relevant to the problem
freq = np.zeros((500,N))
amp = np.zeros((500,N))

for i, hdf5file in zip(np.arange(0,N,1), files):
    amplitude = list()
    frequency = list()

    with h5py.File(hdf5file) as f:
        for dset_name in f:
            dset = f[dset_name]
            frequency.append(dset.attrs['frequency'])
            amplitude.append(dset.attrs['amplitude'])

        freq[:,i] = frequency
        ch2[:,i] = amplitude

for ax, k in zip(axes.flatten(), np.arange(0,N,1)):
    ax.plot(freq[:,k], amp[:,k])

Aucun commentaire:

Enregistrer un commentaire