0

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:

  1. How can I fix this null issue?

  2. How can I get one hour steps? x values should represent a day hours [00:00, ..., 23:00].

screenshot

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
jess
  • 81
  • 1
  • 7

1 Answers1

2

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')))

enter image description here

Miguel Trejo
  • 5,913
  • 5
  • 24
  • 49
  • thanks so much @Miguel! it works perfectly. I just have another question, it's possible to remove the name of month in the bottom right and the year left? – jess Dec 22 '21 at 08:37
  • yes, with show_offset `formatter = mdates.ConciseDateFormatter(locator, show_offset=False)` – Miguel Trejo Dec 22 '21 at 13:05
  • for the text in the right limits can be changed, for example `axs.set_xlim((np.datetime64('2021-01-01 00:01'), np.datetime64('2021-01-01 23:59')))` – Miguel Trejo Dec 22 '21 at 13:07