【问题标题】:Date/Time not plotting as expected日期/时间未按预期绘制
【发布时间】:2019-12-26 05:59:02
【问题描述】:

我将随着时间的推移绘制一些温度数据,并编写了一个测试程序来看看 Matplotlib 可以为我做些什么。当我绘制日期时间未按预期显示的日期时,会输出日期,但时间是某种类型的计数器,而不是预期的时间。

样本数据:

import pandas as pd

df = pd.DataFrame([
    ['08/16/2019 00:00:00',70 ],['08/17/2019 00:05:00',70.5 ],
    ['08/17/2019 00:10:00',70.5],['08/17/2019 00:15:00',71 ],
    ['08/17/2019 00:20:00',72 ],['08/17/2019 00:25:00',73 ],
    ['08/17/2019 00:30:00',74 ],['08/17/2019 00:35:00',74.5], 
    ['08/17/2019 00:40:00',75 ],['08/17/2019 00:45:00',74.5], 
    ['08/17/2019 00:50:00',73 ],['08/17/2019 00:55:00',75 ],
    ['08/17/2019 01:00:00',72.5],['08/17/2019 01:05:00',78 ],
    ['08/17/2019 01:10:00',78]], columns=['Date Time', 'Temperature'])

df
Out[1]: 
              Date Time  Temperature
0   08/16/2019 00:00:00         70.0
1   08/17/2019 00:05:00         70.5
2   08/17/2019 00:10:00         70.5
3   08/17/2019 00:15:00         71.0
4   08/17/2019 00:20:00         72.0
5   08/17/2019 00:25:00         73.0
6   08/17/2019 00:30:00         74.0
7   08/17/2019 00:35:00         74.5
8   08/17/2019 00:40:00         75.0
9   08/17/2019 00:45:00         74.5
10  08/17/2019 00:50:00         73.0
11  08/17/2019 00:55:00         75.0
12  08/17/2019 01:00:00         72.5
13  08/17/2019 01:05:00         78.0
14  08/17/2019 01:10:00         78.0
import csv
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime

path="/home/mikejs/PythonSandbox/temps.csv"
file = open(path,newline='')
reader = csv.reader(file)
header = next(reader)
dates = []
temps  = []

for row in reader:
    date = datetime.strptime(row[0],'%m/%d/%Y %H:%M:%S')
    dates.append(date)
    temps.append(float(row[1]))

plt.title("Temperatures Over Time")
plt.plot(dates,temps )
plt.ylabel('Temperatues')
plt.xlabel('Date/Time')
plt.xticks(rotation='45')
plt.tight_layout();
plt.savefig('temps.png')
plt.show()

【问题讨论】:

  • 请分享一些示例输入,以便我们了解可能出现的问题。 Matplotlib 有一个完整的date 模块。
  • 这是数据示例:日期时间,温度 08/16/2019 00:00:00,70 08/17/2019 00:05:00,70.5 08/17/2019 00: 10:00,70.5 08/17/2019 00:15:00,71 08/17/2019 00:20:00,72 08/17/2019 00:25:00,73 08/17/2019 00:30: 00,74 08/17/2019 00:35:00,74.5 08/17/2019 00:40:00,75 08/17/2019 00:45:00,74.5 08/17/2019 00:50:00, 73 08/17/2019 00:55:00,75 08/17/2019 01:00:00,72.5 08/17/2019 01:05:00,78 08/17/2019 01:10:00,78
  • @user2461513 使用pandas,然后使用Provide a copy of the data。编辑您的问题并将数据放在那里。

标签: datetime matplotlib plot


【解决方案1】:

您可以使用matplotlib.dates 模块将您的轴转换为日期,然后它会正确解释间距。

以下是使用pandas 重现您的示例的示例:

import pandas as pd
from matplotlib import dates as mdates

df = pd.DataFrame([
    ['08/16/2019 00:00:00',70 ],['08/17/2019 00:05:00',70.5 ],
    ['08/17/2019 00:10:00',70.5],['08/17/2019 00:15:00',71 ],
    ['08/17/2019 00:20:00',72 ],['08/17/2019 00:25:00',73 ],
    ['08/17/2019 00:30:00',74 ],['08/17/2019 00:35:00',74.5], 
    ['08/17/2019 00:40:00',75 ],['08/17/2019 00:45:00',74.5], 
    ['08/17/2019 00:50:00',73 ],['08/17/2019 00:55:00',75 ],
    ['08/17/2019 01:00:00',72.5],['08/17/2019 01:05:00',78 ],
    ['08/17/2019 01:10:00',78]], columns=['Date Time', 'Temperature'])


### make sure you set date as the index (and optionally drop the column)
df.index = pd.to_datetime(df['Date Time'])
df.drop(['Date Time'], axis=1, inplace=True)

下面我用第一次观察绘制样本数据并跳过它。由于比其他时间早 24 小时,您可以注意到间距很大。

plt.figure(figsize=(16,6))
ax1 = plt.subplot(121)
ax1.set_title("Temperatures Over Time")
ax1.plot(mdates.date2num(df.index), df['Temperature'])
ax1.set_ylabel('Temperatues')
ax1.set_xlabel('Date/Time')
ax1.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m %H:%M"))
plt.xticks(df.index, rotation='45')

# fig, ax = plt.subplots()
ax = plt.subplot(122)
ax.plot(mdates.date2num(df[1:].index), df[1:]['Temperature'])
ax.set_title("Temperatures Over Time (skipping first)")
ax.set_xticks(df[1:].index)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m %H:%M"))
plt.xticks(rotation='45')
plt.tight_layout();
# plt.savefig('temps.png')
plt.show()

也用于编辑轴,它具有根据您的需要对其进行格式化的功能。例如,在以下行中,您可以调整格式。

ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m %H:%M"))

【讨论】:

  • plt.subplot(121) 究竟是做什么的?
  • 我在一个图中创建了两个子图。三位数 (121) 依次表示:总行数 (1)、总列数 (2) 和实例(1 表示第一个,2 表示第二个)。它是一个网格系统,我曾经通过绘制 2 个图来证明时间是正确的。
  • 谢谢,您的解决方案有效。我还学到了一些其他的东西。
猜你喜欢
  • 1970-01-01
  • 2020-03-04
  • 2019-05-18
  • 1970-01-01
  • 2019-12-14
  • 1970-01-01
  • 2019-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多