![](/img/trans.png)
[英]Cannot Plot Time alone as x-axis >> TypeError: float() argument must be a string or a number, not 'datetime.time'
[英]how to plot time series where x-axis is datetime.time object in matplotlib?
我正在嘗試繪制第二天晚上9點到下午6點的時間序列數據。 這是我失敗的嘗試。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import time
a=np.array([35,25,24,25,27,28,30,35])
df=pd.DataFrame(index=pd.date_range("00:00", "23:00", freq="3H").time,data={'column1':a})
column1
00:00:00 35
03:00:00 25
06:00:00 24
09:00:00 25
12:00:00 27
15:00:00 28
18:00:00 30
21:00:00 35
重新索引數據從21:00到18:00。 也許有更好的方法來實現這一部分,但這是有效的。
df=df.reindex(np.concatenate([df.loc[time(21,00):].index,df.loc[:time(21,00)].index[:-1]]))
column1
21:00:00 35
00:00:00 35
03:00:00 25
06:00:00 24
09:00:00 25
12:00:00 27
15:00:00 28
18:00:00 30
plt.plot(df.index,df['column1'])
x軸似乎與df.index不匹配。 軸也從00:00開始,而不是21:00。 有沒有人知道一個不涉及使用x軸的字符串標簽的解決方案?
一種簡單的方法是在不明確x軸的情況下繪制數據並更改標簽。 問題是這只有在數據之間的時間不變時才有效。 我知道你說你不想使用字符串標簽,所以我不知道這個解決方案會是你想要的。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import time
a=np.array([35,25,24,25,27,28,30,35])
df=pd.DataFrame(index=pd.date_range("00:00", "23:00",freq="3H").time,data={'column1':a})
df=df.reindex(np.concatenate([df.loc[time(21,00):].index,df.loc[:time(21,00)].index[:-1]]))
# Now we create the figure and the axes
fig,axes=plt.subplots()
axes.plot(df['column1']) # In the x axis will appear 0,1,2,3...
axes.set_xticklabels(df.index) # now we change the labels of the xaxis
plt.show()
這應該是訣竅,並將繪制你想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.