I want to create a plot using Matplotlib to show a time along the x-axis. The following code is a complete minimum workable example:
import random
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import dates as mdates
times = np.arange(0, 5000, 60)
x = [datetime.utcfromtimestamp(val) for val in times]
y = random.sample(range(1, 100), len(x))
formatter = mdates.DateFormatter("%H:%M")
locator = mdates.MinuteLocator(interval=10)
# locator = mdates.MinuteLocator(interval=10, byminute=10)
# locator = mdates.MinuteLocator(interval=10, byminute=[0,10,20,30,40,50])
plt.clf()
plt.gca().xaxis.set_major_formatter(formatter)
plt.gca().xaxis.set_major_locator(locator)
plt.plot(x, y)
plt.grid(True)
plt.xlabel("time [min]")
plt.ylabel("Random number")
plt.show()
Along with a DateFormatter
, it creates the following axis labels:
However, I want the ticks to be made only at every full 10 minutes, i.e., I want ticks at times 15:30, 15:40, 15:50, etc. and not starting at 15:24. So I tried
locator = mdates.MinuteLocator(interval=10, byminute=10)
which gives me an error
ValueError: Invalid rrule byxxx generates an empty set.
but according to the documentation, you also can specify an int value or a list of ints. But even when trying to use a list of ints
locator = mdates.MinuteLocator(interval=10, byminute=[0,10,20,30,40,50])
it still gives the same error!
How can I fix this problem?
If you're listing specific integers, I don't think you need to specify the interval.
Change this:
locator = mdates.MinuteLocator(interval=10, byminute=[0,10,20,30,40,50])
To this:
locator = mdates.MinuteLocator(byminute=[0,10,20,30,40,50])