为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

眼眸繁星 2022-12-06 15:11:30
我想matplotlib用数据绘制条形图:     valueHour    0    1001    2002    1003    2004    1005    2006    2007    2008    1009    20010   10011   10012   20013   10014   10015   20016   10017   20018   10019   10020   10021   20022   10023   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正确?
查看完整描述

1 回答

?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

你可以试试这个。利用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')


查看完整回答
反对 回复 2022-12-06
  • 1 回答
  • 0 关注
  • 84 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信