我打算使用散列图针对 Dvicetimestamp 对另一列 ID 绘制数据帧df。数据框df看起来像这样:
Index Dvicetimestamp eventName ID
0 01:11:24.210000 ABC 4
1 01:11:30.224000 CDE 6
2 02:16:30.210000 CDE 6
3 02:27:30.211000 CDE 6
2 01:30:40.212000 DEF 8
3 01:35:23.122000 CDE 6
4 02:22:22.145000 CDE 6
5 02:26:11.222000 DEF 8
... ... ...
但是,我打算创建一个图例,以使每种唯一颜色在图形上显示其 ID 和相应的 eventName 。在显示图表时,我如何使x轴刻度线间隔为1小时。但是,我得到了错误:KeyError:0
这是我尝试过的代码:
nums = np.array([time2num(di) for di in df['Dvicetimestamp']])
def my_formatter(x, pos=None):
d = matplotlib.dates.num2date(x)
if len(str(d.minute)) == 1:
mn = '0{}'.format(d.minute)
else:
mn = str(d.minute)
if len(str(d.hour)) == 1:
hr = '0{}'.format(d.hour)
else:
hr = str(d.hour)
return hr+':'+mn
major_formatter=FuncFormatter(my_formatter)
fig, ax = plt.subplots()
ax.xaxis.set_major_formatter(major_formatter)
labels = set(df['ID']);
ax.scatter(nums,df['ID'],s=20,c=df['ID'], marker = 'o', cmap = cm.tab20 )
xmin = df['Dvicetimestamp'][0]-datetime.timedelta(hours=1)
xmax = df['Dvicetimestamp']
[len(df['DviceTimeStamp'])-1]+datetime.timedelta(hours=1)
ax.set_xlim((xmin,xmax))