从命令行绘制输入文件中的数据

时间:2014-10-10 18:51:40

标签: python matplotlib plot

我已经获得了一个名为“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)

数据文件是:

# 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)    

3 个答案:

答案 0 :(得分:1)

有一个名为numpy的{​​{1}}函数将ascii文件加载到loadtxt数组中:

numpy

答案 1 :(得分:0)

尝试将循环更改为:

for line in f:
    words = line.split()
    tList.append(int(words[0]))
    density.append(float(words[1]))

因为代码可以使用数字索引快速进行模糊处理,所以可以使用元组解包将值分配给有意义的变量名,例如:

for line in f:
    temp,dens = line.split()
    tList.append(int(temp))
    density.append(float(dens))

答案 2 :(得分:0)

你使用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是必需的,因为您的数据是按列排列的。 'rx'绘制红色十字架,因为您不想连接点。

函数genfromtxt是加载了pylab的numpy的一部分。

我建议不要使用pylab,而是自己加载相应的模块,在这种情况下matplotlib.pyplotnumpy

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()

如果您有多个导入

,请不要使用from ... import *
相关问题