簡體   English   中英

如何在 matplotlib xticks 中將 int64 類型的索引列轉換為小時

[英]How to convert index column of int64 type to hour in matplotlib xticks

我想 plot 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的圖形。 預計 output 將xticks更改為時間格式,即hour:minute ,例如01:0002:00等... Hourint64類型。

圖表代碼:

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轉換為 Time(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

你可以試試這個。 使用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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM