[英]Plotting data from input file from command line
我得到了一個名為“ 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)
有一個名為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()
嘗試將循環更改為:
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))
您使用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
函數是pypy加載的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()
並且不要使用from ... import *
如果from ... import *
次數超過1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.