I have date index available in the following format:
JavaScript
x
9
1
['2021-09-07 07:00:00' '2021-09-07 06:00:00' '2021-09-07 05:00:00'
2
'2021-09-07 04:00:00' '2021-09-07 03:00:00' '2021-09-07 02:00:00'
3
'2021-09-07 01:00:00' '2021-09-07 00:00:00' '2021-09-06 23:00:00'
4
'2021-09-06 22:00:00' '2021-09-06 21:00:00' '2021-09-06 20:00:00'
5
'2021-09-06 19:00:00' '2021-09-06 18:00:00' '2021-09-06 17:00:00'
6
'2021-09-06 16:00:00' '2021-09-06 15:00:00' '2021-09-06 14:00:00'
7
'2021-09-06 13:00:00' '2021-09-06 12:00:00' '2021-09-06 11:00:00'
8
'2021-09-06 10:00:00' '2021-09-06 09:00:00' '2021-09-06 08:00:00']
9
But the following code generates wrong graph:
JavaScript
1
10
10
1
if __name__ == '__main__':
2
df = generate_signal_df_hourly()
3
print(df.index.values)
4
5
fig, ax = plt.subplots()
6
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
7
ax.bar(df.index.values, df['close'])
8
plt.xticks(rotation=20, ha='left')
9
plt.show()
10
Advertisement
Answer
Your dataframe index is likely in the wrong format: str
. You can check this with df.info()
, if you have something like:
JavaScript
1
4
1
2
Index: 17 entries, 2021-09-06 00:00:00 to 2021-09-08 00:00:00
3
4
If that’s the case, you need to convert index type from str
to datetime
with:
JavaScript
1
2
1
df.index = pd.to_datetime(df.index)
2
Code example:
JavaScript
1
20
20
1
import matplotlib.pyplot as plt
2
import pandas as pd
3
import numpy as np
4
import matplotlib.dates as mdates
5
6
7
df = pd.DataFrame({'date': pd.date_range(start = '2021-09-06', end = '2021-09-08', freq = '3H')})
8
df['close'] = np.random.randn(len(df))
9
df['date'] = df['date'].astype(str)
10
df = df.set_index('date')
11
df.index = pd.to_datetime(df.index)
12
13
14
fig, ax = plt.subplots()
15
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
16
ax.xaxis.set_major_locator(mdates.HourLocator(interval = 3))
17
df['close'].plot(kind = 'bar', ax = ax)
18
plt.xticks(rotation=20, ha='left')
19
plt.show()
20
Without to_datetime
conversion:
With to_datetime
conversion: