Reputation: 5155
I want to plot matplotlib
bar graph with data:
value
Hour
0 100
1 200
2 100
3 200
4 100
5 200
6 200
7 200
8 100
9 200
10 100
11 100
12 200
13 100
14 100
15 200
16 100
17 200
18 100
19 100
20 100
21 200
22 100
23 200
which returned graph with integers 1 to 23
as xticks
. Expected output is to have the xticks
changed to time format, i.e. hour:minute
, such as 01:00
, 02:00
, etc... Hour
was in int64
type.
Code for graph:
fig, ax = plt.subplots(figsize=(30,10))
plt.xticks(np.arange(0, 24), fontsize=30)
plt.bar(x.index, x.value, color = 'c')
# x.index = pd.to_datetime(x.index, format='%H').strftime('%H')
# ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))
# x.index = [datetime.time(i, 0) for i in x.index]
ax.get_yaxis().set_major_formatter(
ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
plt.xlabel('Hour', fontsize=35)
plt.ylabel('Value', fontsize=35)
I tried to convert index column Hour
into Time(hour) format with:
x.index = pd.to_datetime(x.index, format='%H').strftime('%H')
which caught error:
TypeError: the dtypes of parameters x (object) and width (float64) are incompatible
Also tried ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))
and x.index = [datetime.time(i, 0) for i in x.index]
based on other similar questions but none worked.
Why isn't it working? Is it because of the index form or I didn't change the Hour
column from int64
to time
correctly?
Upvotes: 1
Views: 415
Reputation: 20689
You can try this. Use pd.Index.astype
pd.to_datetime(df.index.astype('object'),format='%H').strftime('%H:%M')
Index(['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00',
'08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00',
'16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'],
dtype='object', name='Hour')
Upvotes: 1