Skip to content Skip to sidebar Skip to footer

Plot Date And Time (x Axis) Versus A Value (y Axis) Using Data From File

I have data in a file (.dat) in the format of %dd %mm %yyyy %HH %MM %SS value separated by spaces. I would like to plot the day, month, year and time on the x-axis, and the valu

Solution 1:

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

With file.dat being e.g.

01062013 00000024.2302062013 01000022.2303062013 02000021.4304062013 03000024.3204062013 14300023.4206062013 03000024.3207062013 19200023.5408062013 03000026.2308062013 19000024.4310062013 12400023.22

the output becomes like this: enter image description here

Post a Comment for "Plot Date And Time (x Axis) Versus A Value (y Axis) Using Data From File"