Reputation: 101
I'm trying to create plot with x-axis as hourly data (step = 1 hour). Although I defined an x-data as array with hourly data, I've gotten x-values with 00:00 (see screenshot).
import pandas as pd
import matplotlib.mdates as mdates
range_hour = pd.date_range(start='2021-01-01', periods=24, freq='H')
xdata_hour = range_hour.hour.values
h_fmt = mdates.DateFormatter('%H:%M')
plot(xdata_hour, ydata)
ax.xaxis.set_major_formatter(h_fmt)
So my questions are:
How can I fix this null issue?
How can I get one hour steps? x values should represent a day hours [00:00, ..., 23:00].
Upvotes: 0
Views: 5371
Reputation: 6677
If single date hourly values try with ConciseDateFormatter it attempts to
figure out the best format to use for the date, and to make it as compact as possible, but still be complete.
you can also define how many hour values to show with maxticks
params inside AutoDateLocator
. See example below
Full Example
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
# Generate 24 hour data
base = datetime.datetime(2021, 1, 1)
dates = [base + datetime.timedelta(hours=(i)) for i in range(24)]
# Generate 24 random values
y = np.random.choice(range(10), 24)
fig, ax = plt.subplots(1, 1, figsize=(14, 6))
# Change tickvalues to show all 24 hour values or less values
locator = mdates.AutoDateLocator(minticks=12, maxticks=24)
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
ax.plot(dates, y)
# Set x limit values to same day
ax.set_xlim((np.datetime64('2021-01-01 00:00'), np.datetime64('2021-01-01 23:59')))
Upvotes: 2