从ASCII文件在Python中绘制数据
我有一个ASCII文件(可以当作txt文件打开)。这个文件里有数据(是一个数值模拟的结果),数据的格式是每41个数据用空格分开,然后换行,接着再写41个数据,依此类推。
我想从这个文件中提取数据,并在图的x轴上画出从一个变量值(这个值是我在另一个Python文件中提取的)开始的数字,这些数字是以一个固定的值递增的;而在y轴上,我想画出ASCII文件最后一行的数据,按顺序排列。
我尝试过,但不知道为什么得到的图是空的。
1 个回答
0
这个是 x 值
# read your data from your files, # here I read them from the terminal. # Remember that what you read is always a string, # and you have to convert to the appropriate type # (here you must convert to `float`) x0 = float(input('X start at: ')) dx = float(input('X increment: ')) npts = 41 x = np.linspace(x0, x0+dx*npts-dx, npts)
读取数据时,文件对象有一个
.readlines()
方法,这个方法会返回一个字符串列表,每一行对应一个字符串。我们可以用[-1]
来获取这个列表中的最后一行,最后我们把这一行拆分成一个字符串列表,然后再把这些字符串转换成float
类型的数字。last_line = open( # 123456789+123456789+123456789+123456789+1 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.txt' ).readlines()[-1] y = [float(n) for n in last_line.split()]
绘图,没有评论
import matplotlib.pyplot as plt plt.plot(x, y) plt.show()