我想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')
添加回答
舉報
0/150
提交
取消