I have a lot of data files with the following structure,
datafile_1.txt
2.400000000e-01 7.200000000e-01
2.640000000e-01 7.920000000e-01
2.768855359e-01 8.306566078e-01
2.904000000e-01 8.712000000e-01
3.000000000e-01 9.001250000e-01
datafile_2.txt
4.800000000e-01 1.040000000e+00
5.034282471e-01 1.090761202e+00
5.280000000e-01 1.144000000e+00
I have the following code that I use to plot the data,
import numpy as np
import matplotlib.pyplot as plt
import csv
import os
path = os.path.join(os.path.expanduser('~'), 'Python', 'Simulations', 'DATAFILES', '')
files = ['datafile_1', 'datafile_2']
for file in files:
with open(path + file + '.txt') as datafile:
for line in datafile:
lines = datafile.readlines()
x0_1 = [float(line.split()[0]) for line in lines]
y0_1 = [float(line.split()[1]) for line in lines]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x0_1, y0_1, 'r', label=file)
...
...
This code gives me two separate plots --> One for datafile_1.txt and another for datafile_2.txt. But I want the two graphs in the same plot. To do this I wrote these lines,
x0_1 = []
y0_1 = []
for file in files:
with open(path + file + '.txt') as datafile:
for line in datafile:
lines = datafile.readlines()
x0_1[file] = [float(line.split()[0]) for line in lines]
y0_1[file] = [float(line.split()[1]) for line in lines]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x0_1[datafile_1], y0_1[datafile_2], 'r', label=datafile_1)
ax1.plot(x0_1[datafile_2], y0_1[datafile_2], 'g', label=datafile_2)
...
...
I am not sure if this is the right way to do it. But I get an error --> TypeError: list indices must be integers or slices, not str.
So, how do I iterate over the files and store the data as x0_1[datafile_1], y0_1[datafile_1], x0_1[datafile_2], y0_1[datafile_2]?
ax1.plot(x0_1[datafile_1], y0_1[datafile_2], 'r', label=datafile_1)Where are the variablesdatafile_1anddatafile_2defined? You probably intend to use a dictionary and accessx0_1['datafile_1']