[英]Plotting data from input file from command line
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? 我得到了一个名为“ density_air.dat”的数据文件,我需要从每一列中提取数据并将它们放入自己的列表中(即tList将以“ -10”开头的列中包含值,而密度将包含值在以“ 1.341”开头的列中,然后需要绘制列表。我在用此数据填充列表时遇到问题...有什么帮助吗?
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)
There is a numpy
function called loadtxt
which loads ascii files into numpy
arrays: 有一个名为
loadtxt
的numpy
函数,它将ascii文件加载到numpy
数组中:
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()
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, eg: 因为使用数字索引可以使代码很快变得混乱,所以可以使用元组拆包将值分配给有意义的变量名,例如:
for line in f:
temp,dens = line.split()
tList.append(int(temp))
density.append(float(dens))
You use pylab for plotting, so why not for reading in? 您使用pylab进行绘图,那么为什么不读入呢?
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. unpack=True
是必需的,因为您的数据按列排列。 'rx'
draws red crosses, as you do not want to connect points. 'rx'
绘制红叉,因为您不想连接点。
The function genfromtxt
is part of numpy
which is loaded with pylab. genfromtxt
函数是pypy加载的numpy
一部分。
I would recommand to not use pylab but load the respective modules yourself, in this case matplotlib.pyplot
and numpy
: 我建议不要使用pylab,而是自己加载各个模块,在这种情况下,请使用
matplotlib.pyplot
和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 并且不要使用
from ... import *
如果from ... import *
次数超过1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.