Skip to main content
 首页 » 编程设计

python之从python中的txt文件中绘制选定的值

2024年12月31日9mfrbuaa

我有一个txt文件,包含2016-2018年每一天每一秒对应的数据(每天总结大约1400多个数据),首先,我选择了特定日期的数据:05.01.2016,然后我想使用当天的数据在 python 中绘制图形

以下代码用于选择值和绘制图形:

if '01.05.2016' in row: #select the value in day 05.01.2016 
    x = [row.split()[6]]  
    y = [row.split()[2]] 
fig = plt.figure() 
ax1 = fig.add_subplot(111) 
ax1.plot(x,y) 
plt.ylim((200,800)) 
plt.show() 

如果我使用命令:

x = [row.split()[6]]  
y = [row.split()[2]] 
print(x,y) 

那么 x 和 y come 就成功出来了(以几对 x-y 值为例):

['01.05.2016/15:43:00'] ['499'] 
['01.05.2016/15:44:00'] ['501'] 
['01.05.2016/15:45:00'] ['502'] 
['01.05.2016/15:46:00'] ['502'] 

我原来的 txt.file 的一部分是这样的:

01.05.2016  15:43:00    499 U   42491,65486  -0,01   01.05.2016/15:44:00 
01.05.2016  15:44:00    501 U   42491,65556  0,01   01.05.2016/15:45:00  
01.05.2016  15:45:00    502 U   42491,65625  0,02   01.05.2016/15:46:00  
01.05.2016  15:46:00    503 U   42491,65694  0,03   01.05.2016/15:47:00  

但是如果我继续写绘制图​​形的命令。该图只显示一对(最后一对)x-y 值,我的图是这样的:

谁能帮帮我?

请您参考如下方法:

你可以这样做:

import matplotlib.pyplot as plt 
df = pd.read_csv('file.txt', sep = '\t', names = ["col", "col1", "val", "col3", "col4", "time"]) 
df['time'] = pd.to_datetime(df['time'], format='%d.%m.%Y/%H:%M:%S') 
df.set_index('time', inplace=True) 
match_timestamp = "01.05.2016" 
df1 = df.loc[df.index.strftime("%m.%d.%Y") == match_timestamp] 
print df1 
df1['val'].plot() 
plt.show() 

注意 pd.read_csv 中的分隔符是什么

例子

输入:

01.04.2016  15:46:00    503 42491,65694 0,03    02.05.2016/15:47:00 
01.05.2016  15:43:00    499 42491,65486 -0,01   01.05.2016/15:44:00 
01.05.2016  15:44:00    501 42491,65556 0,01    01.05.2016/15:45:00  
01.05.2016  15:45:00    502 42491,65625 0,02    01.05.2016/15:46:00  
01.05.2016  15:46:00    503 42491,65694 0,03    01.05.2016/15:47:00  
02.05.2016  15:46:00    503 42491,65694 0,03    02.05.2016/15:47:00 

df1:

                            col      col1   val         col3   col4 
time                                                                
2016-01-05 15:44:00  01.05.2016  15:43:00   499  42491,65486  -0,01 
2016-01-05 15:45:00  01.05.2016  15:44:00   501  42491,65556   0,01 
2016-01-05 15:46:00  01.05.2016  15:45:00   502  42491,65625   0,02 
2016-01-05 15:47:00  01.05.2016  15:46:00   503  42491,65694   0,03