使用来自文件的数据,绘制日期和时间(x轴)与值(y轴)的图表。

5

我有一个以以下格式存储的数据文件(.dat):

%dd %mm %yyyy %HH %MM %SS value

数据各部分之间用空格隔开。我想将日期和时间(日、月、年、小时、分钟、秒)作为x轴,数值作为y轴进行绘图。由于有很多非常大的数据文件需要分析,因此应该始终从文件中读取它们。

我最近尝试了以下方法:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from time import gmtime, strftime
date, time, level = np.loadtxt('my_file.txt', unpack=True, usecols = (0,1,2,3), converters={ 0,1: mdates.strpdate2num('%dd/%mm/%YY %HH:%MM')}) #read format of file
# then to plot 
plt.plot_date(x=date, y=level, fmt='%dd/%mm/%YY %HH:%MM') # fmt is changed from r- 
plt.title('title')
plt.ylabel('Waterlevel (m)')
plt.grid(True)
plt.show()
1个回答

13

如果我正确理解了您的问题,我相信这是一个可能的解决方案:

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

# Converter function
datefunc = lambda x: mdates.date2num(datetime.strptime(x, '%d %m %Y %H %M %S'))

# Read data from 'file.dat'
dates, levels = np.genfromtxt('file.dat',    # Data to be read
                              delimiter=19,  # First column is 19 characters wide
                              converters={0: datefunc}, # Formatting of column 0
                              dtype=float,   # All values are floats
                              unpack=True)   # Unpack to several variables

fig = plt.figure()
ax = fig.add_subplot(111)

# Configure x-ticks
ax.set_xticks(dates) # Tickmark + label at every plotted point
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y %H:%M'))

ax.plot_date(dates, levels, ls='-', marker='o')
ax.set_title('title')
ax.set_ylabel('Waterlevel (m)')
ax.grid(True)

# Format the x-axis for dates (label formatting, rotation)
fig.autofmt_xdate(rotation=45)
fig.tight_layout()

fig.show()

有一个名为 file.dat 的文件。

01 06 2013 00 00 00 24.23
02 06 2013 01 00 00 22.23
03 06 2013 02 00 00 21.43
04 06 2013 03 00 00 24.32
04 06 2013 14 30 00 23.42
06 06 2013 03 00 00 24.32
07 06 2013 19 20 00 23.54
08 06 2013 03 00 00 26.23
08 06 2013 19 00 00 24.43
10 06 2013 12 40 00 23.22
输出结果将会变成这样: 在此输入图片描述

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接