使用文件中的数据绘制日期和时间(x轴)与值(y轴)的关系 [英] Plot date and time (x axis) versus a value (y axis) using data from file

查看:133
本文介绍了使用文件中的数据绘制日期和时间(x轴)与值(y轴)的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文件(.dat)中具有

I have data in a file (.dat) in the format of

%dd%mm%yyyy%HH%MM%SS值

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

以空格分隔.我想在x轴上绘制日期,月份,年份和时间,并在y轴上绘制值.应该总是从文件中读取它,因为我有很多文件要分析很大.

separated by spaces. I would like to plot the day, month, year and time on the x-axis, and the value on the y-axis. It should always be reading it from the file, as I have many files that are very large to analyze.

我最近的尝试:

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()

推荐答案

如果我正确理解了您的问题,我认为这是可能的解决方案:

If I have understood your problem correctly, I believe this is a possible solution:

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

输出如下所示:

这篇关于使用文件中的数据绘制日期和时间(x轴)与值(y轴)的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆