使用python绘制具有时间间隔的值时没有显示图表

数据挖掘 Python 熊猫
2022-02-20 01:15:50

我有一个包含值以及日期和时间的大型数据集。所以我想用时间和日期绘制价值图。所以我写了一个时差代码。之后,我尝试将价值存储到那个时差中。之后我尝试绘制它。它在没有图表的情况下运行。谁能帮我解决这个错误?这是我的代码:

x= df1,iloc[:,2]
time_interval = 14400 #interval in seconds (14400s = 360 minutes)
date_array = []
date_array.append(pd.to_datetime(df1['date'][0]).date())
start_time = []
end_time   = []
temp_date  = pd.to_datetime(df1['date'][0]).date()
start_time.append(pd.to_datetime(df1['time'][0], format='%H:%M:%S').time())
for i in range(len(df1['date'])):
cur_date = pd.to_datetime(df1['date'][i]).date()
if( cur_date > temp_date):
    end_time.append(pd.to_datetime(df1['time'][i-1], format='%H:%M:%S').time())
    start_time.append(pd.to_datetime(df1['time'][i], format='%H:%M:%S').time())
    date_array.append(cur_date)
    temp_date = cur_date
    end_time.append(pd.to_datetime(df1['time'][len(df1['date'])-1], format='%H:%M:%S').time())
  datetime_array = []
  for i in range(len(date_array)):
s_time = datetime.datetime.combine(date_array[i],start_time[i])
e_time = datetime.datetime.combine(date_array[i],  end_time[i])

timediff = (e_time - s_time)
#num_periods = int(timediff.total_seconds()/t3ime_interval) +1 
num_periods = abs(int(timediff.total_seconds()/time_interval)) + 1 
time_list = pd.date_range(start=s_time, end = e_time, periods=num_periods ).to_pydatetime()
datetime_array.extend(time_list)
time_stamps = [datetime.datetime.strftime(t,'%H:%m:%S') for t in datetime_array]
x = np.zeros([num_periods], dtype='timedelta64[s]')
plt.xticks(np.arange(num_periods), time_stamps)

我的 csv 文件:

在此处输入图像描述

运行代码输出后是这样的:

在此处输入图像描述

图片:

在此处输入图像描述

1个回答

在 python 中,您通常拥有所有可用的库。有时很难找到,但你应该很少需要写出这么多代码。试试这个。

我使用与您相同的日期格式创建了一些虚拟数据:

import pandas as pd
import matplotlib.pyplot as plt

data = {'date': ['08/06/2018', '8/6/2018', '8/6/2018', '9/6/2018'],
        'time': ['6:15:00', '12:45:00', '18:15:00', '6:15:00'],
        'x2': [1, 4, 8, 6]}

现在我们将用这个虚拟数据制作一个 pandas DataFrame

df = pd.DataFrame(data)

现在我们可以通过首先将日期和时间连接在一起并用空格分隔来获得我们的 x 轴日期时间。然后我们将让 pandas 解析这些日期时间。

datetimes = pd.to_datetime(df['date'] + ' ' + df['time'], 
                           format='%d/%m/%Y %H:%M:%S')

然后,您可以使用

plt.plot(datetimes, df['x2'])

在此处输入图像描述


将您的 csv 文件放入您的工作区。然后您可以使用以下代码

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv(r'temp.csv')
datetimes = pd.to_datetime(df['date'] + ' ' + df['time'], 
                           format='%d/%m/%Y %H:%M:%S')

plt.plot(datetimes, df['x'])
plt.show()

在此处输入图像描述


import matplotlib.dates as mdates

fig, ax = plt.subplots(1)
fig.autofmt_xdate()

plt.plot(datetimes, df['x'])
plt.xticks(rotation=90)

xfmt = mdates.DateFormatter('%d-%m-%y %H:%M')
ax.xaxis.set_major_formatter(xfmt)
plt.show()

在此处输入图像描述