svadhisthana
svadhisthana

Reputation: 163

Plotting a times series using matplotlib with 24 hours on the y-axis

If I run the following, it appears to work as expected, but the y-axis is limited to the earliest and latest times in the data. I want it to show midnight to midnight. I thought I could do that with the code that's commented out. But when I uncomment it, I get the correct y-axis, yet nothing plots. Where am I going wrong?

from datetime import datetime
import matplotlib.pyplot as plt

data = ['2018-01-01 09:28:52', '2018-01-03 13:02:44', '2018-01-03 15:30:27', '2018-01-04 11:55:09']
x = []
y = []

for i in range(0, len(data)):
    t = datetime.strptime(data[i], '%Y-%m-%d %H:%M:%S')
    x.append(t.strftime('%Y-%m-%d')) # X-axis = date
    y.append(t.strftime('%H:%M:%S')) # Y-axis = time

plt.plot(x, y, '.')
# begin = datetime.strptime('00:00:00', '%H:%M:%S').strftime('%H:%M:%S')
# end   = datetime.strptime('23:59:59', '%H:%M:%S').strftime('%H:%M:%S')
# plt.ylim(begin, end)
plt.show()

Edit: I also noticed that the x-axis isn't right either. The data skips Jan 2, but I want that on the axis so the data is to scale.

This is a dramatically simplified version of code dealing with over a year's worth of data with over 2,500 entries.

Upvotes: 1

Views: 4195

Answers (1)

andrew_reece
andrew_reece

Reputation: 21274

If Pandas is available to you, consider this approach:

import pandas as pd
data = pd.to_datetime(data, yearfirst=True)
plt.plot(data.date, data.time)
_=plt.ylim(["00:00:00", "23:59:59"])

plot

Update per comments
X-axis date formatting can be adjusted using the Locator and Formatter methods of the matplotlib.dates module. Locator finds the tick positions, and Formatter specifies how you want the labels to appear.

Sometimes Matplotlib/Pandas just gets it right, other times you need to call out exactly what you want using these extra methods. In this case, I'm not sure why those numbers are showing up, but this code will remove them.

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

f, ax = plt.subplots()
data = pd.to_datetime(data, yearfirst=True)
ax.plot(data.date, data.time)
ax.set_ylim(["00:00:00", "23:59:59"])

days = mdates.DayLocator()
d_fmt = mdates.DateFormatter('%m-%d')
ax.xaxis.set_major_locator(days)
ax.xaxis.set_major_formatter(d_fmt) 

plot2

Upvotes: 4

Related Questions