猿问

如何在matplotlib xticks中将int64类型的索引列转换为小时

我想matplotlib用数据绘制条形图:


     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

返回整数1 to 23为 的图形xticks。预期输出xticks将更改为时间格式,即hour:minute, 01:00,02:00等...类型Hour。int64


图形代码:


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)

我试图将索引列Hour转换为时间(小时)格式:


x.index = pd.to_datetime(x.index, format='%H').strftime('%H')

发现错误:


TypeError: the dtypes of parameters x (object) and width (float64) are incompatible

也尝试过ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M')) 并x.index = [datetime.time(i, 0) for i in x.index]基于其他类似的问题,但没有奏效。


为什么它不起作用?是因为索引形式还是我没有将Hour列从更改int64为time正确?


眼眸繁星
浏览 159回答 1
1回答

翻过高山走不出你

你可以试试这个。利用pd.Index.astypepd.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')
随时随地看视频慕课网APP

相关分类

Python
我要回答