在Python中使用matplotlib.dates绘制毫秒图形

3 投票
1 回答
3073 浏览
提问于 2025-04-16 15:18

我有一些带时间标签的数据,这些数据是用datetime.datetime.strptime格式化的,里面包含了毫秒。数据的时间范围可以从几分钟到几个小时。当我使用pyplot绘图并放大时,发现最小的刻度标记是1秒。看起来matplotlib的TickHelper RRuleLocator只支持到秒的刻度。那么在放大时,有没有办法显示到毫秒的刻度呢?

receivedTime = datetime.datetime.strptime(str(data[1]), "%H:%M:%S.%f")

fig=plt.figure()
ax=fig.add_axes([0.1,0.1,.8,.8])
fig.autofmt_xdate()

ax.plot(times, prices, color='blue', lw=1, drawstyle='steps-post', label = prices)
plt.show()

1 个回答

1

Matplotlib这个工具使用的是类似于Matlab的日期格式,也就是从1970年开始的秒数。如果你的时间是以毫秒为单位的,你需要把这些日期转换成“数字”格式:

import matplotlib.dates as mdates
ntimes = mdates.num2epoch(times / 1000.0)

然后你要绘制的是ntimes,而不是times

撰写回答