Skip to main content
 首页 » 编程设计

python之无法使用 Matplotlib 在 X 轴上显示时间

2024年09月07日12telwanggs

我正在从文件中读取一些数据,然后我必须绘制这些数据以进行可视化表示。 文件中的数据以下列格式存在:

16:08:45,64,31.2 
16:08:46,60,29.3 
16:08:47,60,29.3 
16:08:48,60,29.3 
16:08:49,60,29.3 
. 
. 

此数据存在于具有当前日期的文件中。 该文件包含时间(时:分:秒)、Adc 计数、温度值

我使用以下代码使用 Pandas 从文件中读取数据。

from datetime import datetime 
import pandas as pd 
import matplotlib.pyplot as plt 
import matplotlib.dates as mdates 
 
year = 2018     # For 2018 
''' 
month = input ('Enter Month : ') 
date = input ('Enter Date : ') 
month = int(month) 
date = int(date) 
''' 
# Hardcoded Values for Testing Purpose 
month = 1 
date = 20 
 
headers = ['Time', 'ADC', 'Temperature'] 
filename = '%.2d-%.2d-%.2d.txt' % (month, date, year-2000) 
print (filename) 
 
try: 
    df = pd.read_table( filename, ',', names=headers,\ 
                        engine='python', header=None) 
except: 
    print ('No Such File in Database') 
    print ('Exiting Program') 
    exit() 
 
FMT = '%H:%M:%S' 
df['Time'] = df['Time'].map(lambda x: datetime.strptime(str(x), FMT)) 
df['Time'] = df['Time'].map(lambda x: x.replace(day=date, month=month, year=year)) 
 
plt.plot( df['Time'], df['ADC']) 
 
plt.ylim( [0,200]) 
#plt.gcf().autofmt_xdate() 
plt.show() 

我不明白为什么 x 轴没有正确的值。 是不是因为样本间隔太近(1秒)?

我只想要 X 轴上的时间信息。 请建议我如何得到它。 提前致谢。

更新:

从评论中,我能够找到发生这种情况的原因。 Pandas 将我的日期和时间视为 timestamp 对象,而使用 Matplotlib 绘制它时,它应该是 datetime 对象。 如果我能够将 df['Time'] 从 Timestamp 转换为 datetime,我的问题就会得到解决。 我在网上搜索并找到了 pd.to_datetime,可以为我完成这项工作,但不幸的是,它不起作用。 以下命令将列出我所做的事情。

>>> x = pd.Timestamp( "2018-01-20") 
>>> x 
Timestamp('2018-01-20 00:00:00') 
>>> pd.to_datetime( x, format="%Y-%m-%d") 
Timestamp('2018-01-20 00:00:00') 

正如你在上面看到的,我仍然得到timestamp对象 我再次搜索以检查它为什么不起作用,然后我发现以下行将起作用。

>>> x = pd.Timestamp( "2018-01-20") 
>>> y = pd.to_datetime( x, format="%Y-%m-%d") 
>>> y.to_datetime() 
 
Warning (from warnings module): 
  File "D:\Program Files\Python36\lib\idlelib\run.py", line 457 
    exec(code, self.locals) 
FutureWarning: to_datetime is deprecated. Use self.to_pydatetime() 
datetime.datetime(2018, 1, 20, 0, 0) 
>>>  

要删除此警告,可以使用以下命令。

>>> x = pd.Timestamp( "2018-01-20") 
>>> y = pd.to_datetime( x, format="%Y-%m-%d") 
>>> y.to_pydatetime() 
datetime.datetime(2018, 1, 20, 0, 0) 

现在我在我的项目中测试了这些命令,看看它是否适用于我的数据框,我只取了一个值进行测试。

>>> x = df['Time'][0].to_pydatetime() 
>>> x 
datetime.datetime(2018, 1, 20, 16, 8, 45) 

所以,是的,它正在工作,现在我必须将它应用于完整的数据框列,并且我使用了以下命令。

>>> df['New'] = df['Time'].apply(lambda x: x.to_pydatetime()) 
>>> df['New'][0] 
Timestamp('2018-01-20 16:08:45') 

但还是一样。 我是新手,所以我无法理解我做错了什么。

请您参考如下方法:

首先我们需要一个最小的、可验证的例子:

u = u"""16:08:45,64,31.2 
16:08:46,54,29.3 
16:08:47,36,34.3 
16:08:48,67,36.3 
16:08:49,87,29.3""" 
 
import io 
from datetime import datetime 
import pandas as pd 
import matplotlib.pyplot as plt 
import matplotlib.dates as mdates 
 
year = 2018 
month = 1 
date = 20 
 
headers = ['Time', 'ADC', 'Temperature'] 
 
df = pd.read_table(io.StringIO(u), ',', names=headers,\ 
                        engine='python', header=None) 
 
FMT = '%H:%M:%S' 
df['Time'] = df['Time'].map(lambda x: datetime.strptime(str(x), FMT)) 
df['Time'] = df['Time'].map(lambda x: x.replace(day=date, month=month, year=year)) 
 
plt.plot( df['Time'], df['ADC']) 
 
plt.ylim( [20,100]) 
plt.gcf().autofmt_xdate() 
plt.show() 

使用 pandas 0.20.1 和 matplotlib 2.1 运行此代码,生成了以下图,看起来符合预期:

之所以可行,即使日期是 pandas 时间戳,是因为 matplotlib 在内部使用 pandas 转换器(如果可用)。 如果没有,可以先尝试手动加载它们,

import pandas.plotting._converter as pandacnv 
pandacnv.register() 

如果这也失败了,确实可以尝试将时间戳转换为日期时间对象。

dt = [x.to_pydatetime() for x in df['Time']] 
plt.plot( dt, df['ADC'])