Joel
Joel

Reputation: 99

Plotting Date and an Hour in MatplotLib

I have data that looks like :

Date        Hour    Count1          Count2          Count3
2019-03-12  0       2459416         2459384         2459416
2019-03-12  1       1735044         1735094         1735044
2019-03-12  2       1137516         1137523         1137516
2019-03-12  3       813602          813603          813602
2019-03-12  4       728658          728637          728658

and continues like that for a couple days. I really like the formatting of the Date + Hour in excel but i Cannot figure out how to achieve this in Matplotlib. I've tried combining the Date and Hour to make a datetime column, but been difficult with the Int values of date. I also like the clean formatting excel gives me on the Y-axis when they are separate.

enter image description here

Upvotes: 0

Views: 798

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339795

The following would work with current matplotlib versions.

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


t = np.arange("2019-03-11 00:00", "2019-03-13 08:00", dtype=np.datetime64)
x = np.cumsum(np.random.randn(len(t)))

fig, ax = plt.subplots()

ax.plot(t,x)

ax.xaxis.set_major_locator(mdates.HourLocator(12))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%b-%d"))

ax.xaxis.set_minor_locator(mdates.HourLocator(np.arange(0,24,2)))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%H"))

ax.tick_params(which="major", axis="x", pad=14, size=2)
ax.tick_params(which="minor", axis="x", labelsize=8)

plt.show()

enter image description here

Upvotes: 3

Related Questions