【发布时间】:2017-01-26 10:19:27
【问题描述】:
我想从一个乏味的.dat 文件中绘制一个数量,文件中的#time 列从 0s 扩展到 70s,但我需要仔细查看数据(核能,在这种情况下)从 25 秒到 35 秒。
我想知道是否有一种方法可以操纵时间列和相应的其他列来仅在所需的时间范围内记录和绘制数据。
我已经有一些代码可以为我完成 0-70 年代的工作:
import matplotlib
matplotlib.use('Agg')
import os
import numpy as np
import matplotlib.pyplot as plt
import string
import math
# reads from flash.dat
def getQuantity(folder, basename, varlist):
# quantities[0] should contain only the quantities of varlist[0]
quantities =[]
for i in range(len(varlist)):
quantities.append([])
with open(folder + "/" + basename + ".dat", 'r') as f: # same as f = open(...) but closes the file afterwards.
for line in f:
if not ('#' or 'Inf') in line: # the first line and restarting lines look like this.
for i in range(len(varlist)):
if(varlist[i]==NUCLEAR_ENERGY and len(quantities[i])>0):
quantities[i].append(float(line.split()[varlist[i]])+quantities[i][-1])
else:
quantities[i].append(float(line.split()[varlist[i]]))
return quantities
# end def getQuantity
#create plot
plt.figure(1)
TIME = 0
NUCLEAR_ENERGY = 18
labels = ["time", "Nuclear Energy"]
flashFolder1 = '/home/trina/Pictures' # should be the flash NOT the flash/object folder.
lab1 = '176'
filename = 'flash' # 'flash' for flash.dat
nHorizontal = 1 # number of Plots in Horizontal Direction. Vertical Direction is set by program.
outputFilename = 'QuantityPlots_Nuclear.png'
variables = [NUCLEAR_ENERGY]
#Adjustments to set the size
nVertical = math.ceil(float(len(variables))/nHorizontal) # = 6 for 16 = len(variables) & nHorizontal = 3.
F = plt.gcf() #get figure
DPI = F.get_dpi()
DefaultSize = F.get_size_inches()
F.set_size_inches( DefaultSize[0]*nHorizontal, DefaultSize[1]*nVertical ) #build no of subplots in figure
variables.insert(0,TIME) # time as needed as well
data1 = getQuantity(flashFolder1, filename, variables)
time1 = np.array(data1[0]) #time is first column
for n in [n+1 for n in range(len(variables)-1)]: #starts at 1
ax=plt.subplot(nVertical, nHorizontal, n) #for example (6,3,0 to 15) inside loop for 16 variables
if (min(data1[n])<0.0 or abs((min(data1[n]))/(max(data1[n])))>=1.e-2):
plt.plot(time1, data1[n],label=lab1) #, label = labels[variables[n]])
legend = ax.legend(loc='upper right', frameon=False)
else:
plt.semilogy(time1, data1[n],label=lab1) #, label = labels[variables[n]])
legend = ax.legend(loc='upper right', frameon=False)
plt.savefig(outputFilename)
这是我可以从这段代码中生成的图:
为了您的方便,我还分享了@987654326@ 文件:
https://www.dropbox.com/s/w4jbxmln9e83355/flash.dat?dl=0
非常感谢您的建议。
【问题讨论】:
-
我找不到
Nuclear Energy列...您要绘制哪一列? -
该列是 .dat 文件中的第 19 列,名为“increment”
-
有什么理由不使用
pandas?这是可以让您的生活更轻松的情况之一。 -
hmm,我可以用pandas来做这个,但我就是不知道怎么操作pandas中的列,我用完整的数据来绘制相同的图
标签: python numpy matplotlib dataframe data-manipulation