0

Related to this SO question, but instead of numeric x-axis labels, I'm struggling to add timestamp labels. As an example

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


idx = pd.date_range("2023-06-15", "2023-06-16", freq="1min", inclusive="left")
df = pd.DataFrame(np.random.rand(len(idx), 5), index=idx)

fig, ax = plt.subplots()
im = ax.imshow(df.transpose(), aspect="auto")
fig.colorbar(im, ax=ax)

I'd specifically like to just show the time component, and say just on every 15 minute interval. I am trying to do something like

ax.xaxis.set_major_locator(mdates.MinuteLocator(interval=15))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))

But this just gives

Locator attempting to generate 138241 ticks ([-0.5, ..., 1439.5]), which exceeds Locator.MAXTICKS (1000).

I've tried and failed with various auto formatters and locators. Any help would be appreciated.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
rwb
  • 4,309
  • 8
  • 36
  • 59

1 Answers1

1

Tweaking this answer a bit, while increasing the figsize.

fig, ax = plt.subplots(figsize=(30,10))

x_lims = mdates.date2num(idx)
extent = [x_lims[0], x_lims[-1], 0, 5]

im = ax.imshow(df.transpose(), extent=extent, aspect="auto")
fig.colorbar(im, ax=ax)

ax.xaxis_date()
ax.xaxis.set_major_locator(mdates.MinuteLocator(byminute=[0, 15, 30, 45]))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))
fig.autofmt_xdate()

Output:

enter image description here

Or very similarly:

x_lims = mdates.date2num(["2023-06-15", "2023-06-16"])
extent = [x_lims[0], x_lims[1], 0, 5]
rwb
  • 4,309
  • 8
  • 36
  • 59
BigBen
  • 46,229
  • 7
  • 24
  • 40