【问题标题】:Plot date and time (x axis) versus a value (y axis) using data from txt file (Python)使用 txt 文件 (Python) 中的数据绘制日期和时间(x 轴)与值(y 轴)
【发布时间】:2014-09-15 11:02:50
【问题描述】:

大家好,下面是我尝试的代码,我如何绘制日期和时间(x 轴)与值(y 轴)

import matplotlib.pyplot as plt

x = []
y = []
t = []

fig = plt.figure()
rect = fig.patch
rect.set_facecolor('#31312e')

readFile = open('data.txt', 'r')
sepFile = readFile.read().split('\n')
readFile.close()

for idx, plotPair in enumerate(sepFile):
    if plotPair in '. ':
       # skip. or space
       continue
    if idx > 1:  # to skip the first line
        xAndY = plotPair.split(',')
        time_string = xAndY[0]
        t.append(time_string)
        y.append(float(xAndY[1]))

ax1 = fig.add_subplot(1, 1, 1, axisbg='blue')
ax1.plot(t, y, 'c', linewidth=3.3)

plt.title('IRRADIANCE')
plt.xlabel('TIME')

plt.show()

这是我的 txt 文件:

TimeStamp,Irradiance
21/7/2014 0:00,0.66
21/7/2014 0:00,0.71
21/7/2014 0:00,0.65
21/7/2014 0:00,0.67
21/7/2014 0:01,0.58
21/7/2014 0:01,0.54
21/7/2014 0:01,0.63
21/7/2014 0:01,0.65
21/7/2014 0:02,0.64
21/7/2014 0:02,0.63
21/7/2014 0:02,0.63
21/7/2014 0:02,0.64
.
.
. 
.
22/7/2014 23:57,0.53
22/7/2014 23:58,0.69
22/7/2014 23:58,0.61
22/7/2014 23:58,0.65
22/7/2014 23:58,0.59
22/7/2014 23:59,0.63
22/7/2014 23:59,0.67
22/7/2014 23:59,0.68
22/7/2014 23:59,0.58

但它似乎不起作用(我的代码): ValueError: 时间数据 '' 与格式 '%d/%m/%Y %H:%M' 不匹配

【问题讨论】:

  • time_string 是什么样的?它是str 的类型吗?

标签: python datetime graph


【解决方案1】:
#!/usr/bin/env python
#-*- coding:utf-8 -*-

from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

x = []
y = []
t = []

fig = plt.figure()
rect = fig.patch
rect.set_facecolor('#31312e')

readFile = open('C:\\Temp\\001.txt', 'r')
sepFile = readFile.read().split('\n')
readFile.close()

for idx, plotPair in enumerate(sepFile):
    if plotPair in '. ':
        # skip. or space
        continue
    if idx > 1:  # to skip the first line
        xAndY = plotPair.split(',')
        time_string = xAndY[0]
        time_string1 = datetime.strptime(time_string, '%d/%m/%Y %H:%M')
        t.append(time_string1)
        y.append(float(xAndY[1]))

ax1 = fig.add_subplot(1, 1, 1, axisbg='white')
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y %H:%M'))
ax1.plot(t, y, 'c', linewidth=3.3)

plt.title('IRRADIANCE')
plt.xlabel('TIME')
fig.autofmt_xdate(rotation=45)
fig.tight_layout()
fig.show()

a = raw_input('enter to stop...')

【讨论】:

  • 当我运行模块时,我可以看到图表,但在 x 轴上我只能看到时间,而不能看到日期。
  • @toothberry 您希望 x 轴采用哪种格式? 2014-07-22 或 2014-07 还是?
  • 例如。 22/7/2014 23:57
  • @toothberry 那你就不需要strptime(),只需要在time_string = xAndY[0]之后的t.append(time_string)。
  • 所以整个 'datetime_obj = datetime.strptime(time_string, '%d/%m/%Y %H:%M') 已经过时了?
猜你喜欢
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
相关资源
最近更新 更多