Reputation: 11
I have been given a data file called "density_air.dat" and i need to take the data from each column and put them into their own lists (ie tList will hold the values in column starting with "-10" and density will hold values in column starting with "1.341". The lists then need to be plotted. I am having trouble populating the lists with this data...any help?
from scitools.std import *
import sys
import pylab as pl
inFile = sys.argv[-1]
f = open(inFile, 'r')
for x in range(4):
f.readline()
tList = []
density = []
for line in f:
words = line.split()
for x in words:
tList.append(words[x])
density.append(words[x])
f.close()
plot(tList, density)
The data file is:
# Density of air at different temperatures, at 1 atm pressure
# Column 1: temperature in Celsius degrees
# Column 2: density in kg/m^3
-10 1.341
-5 1.316
0 1.293
5 1.269
10 1.247
15 1.225
20 1.204
25 1.184
30 1.164
# Source: Wikipedia (keyword Density)
Upvotes: 1
Views: 354
Reputation: 147
There is a numpy
function called loadtxt
which loads ascii files into numpy
arrays:
import numpy as np
import matplotlib.pylab as plt
import sys
inFile = sys.argv[-1]
temperature, density = np.loadtxt(inFile,unpack=True)
plt.plot(temperature, density,'ko')
plt.show()
Upvotes: 1
Reputation: 15017
You use pylab for plotting, so why not for reading in?
import sys
import pylab as pl
inFile = sys.argv[-1]
temperature, density = pl.genfromtxt(inFile, unpack=True)
pl.plot(temperature, densitiy, 'rx')
pl.show()
unpack=True
is needed because your data is aranged in columns.
'rx'
draws red crosses, as you do not want to connect points.
The function genfromtxt
is part of numpy
which is loaded with pylab.
I would recommand to not use pylab but load the respective modules yourself, in this case matplotlib.pyplot
and numpy
:
import sys
import matplotlib.pyplot as plt
import numpy as np
inFile = sys.argv[-1]
temperature, density = np.genfromtxt(inFile, unpack=True)
plt.plot(temperature, densitiy, 'rx')
plt.show()
And don't use from ... import *
if you have more than 1 import
Upvotes: 0
Reputation: 169464
Try changing the loop to:
for line in f:
words = line.split()
tList.append(int(words[0]))
density.append(float(words[1]))
Because code can quickly get obfuscated using numerical indexes you can use tuple unpacking to assign the values to meaningful variable names, e.g.:
for line in f:
temp,dens = line.split()
tList.append(int(temp))
density.append(float(dens))
Upvotes: 0