You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在matplotlib中将毫秒级x轴标注为datetime格式且不影响矩形绘制

我们可以通过自定义Matplotlib的X轴格式化函数实现需求,完全不需要修改原有矩形绘制逻辑,仅需额外做3处改动:

  1. 导入FuncFormatter格式化工具
  2. 编写自定义数值转时间字符串的格式化函数
  3. 将X轴主刻度格式化器绑定为自定义函数

修改后完整代码

import pandas
from matplotlib import pyplot
from matplotlib.collections import PolyCollection
from matplotlib.ticker import MultipleLocator, FuncFormatter # 新增导入FuncFormatter

df = pandas.read_csv('thing.csv')

vert = {"upright":1, "supine":2, "lying_left":3, "prone":4, "lying_right":5, "unknown":6}

fig, (ax1) = pyplot.subplots(1, 1, figsize=(15,5))

# 新增:自定义时间格式化函数
def timestamp_to_str(x, pos):
    # 输入的x是毫秒级时间戳数值,转为datetime后格式化输出
    return pandas.to_datetime(x, unit='ms').strftime('%m-%d %H:%M')

# first plot of positions over time
# get the computed body positions as bars
bars = []
colors = []
for i,row in df.iterrows():
    h = vert[row['body_position']]
    t = row['timestamp']
    
    rect = [(t - 59000, h - 0.4), (t - 59000, h + 0.4), (t, h + 0.4), (t, h - 0.4), (t - 59000, h - 0.4)]
    bars.append(rect)
    colors.append("C" + str(h-1))

bars = PolyCollection(bars, facecolors=colors)
ax1.add_collection(bars)

ax1.autoscale()
ax1.xaxis.set_major_locator(MultipleLocator(60000))
ax1.xaxis.set_major_formatter(FuncFormatter(timestamp_to_str)) # 绑定自定义格式化器
pyplot.xticks(rotation=45) # 可选:旋转标签避免重叠

ax1.set_yticks(sorted(vert.values()))
ax1.set_yticklabels(sorted(vert, key=vert.get))

pyplot.tight_layout()
pyplot.show()

实现原理

X轴底层还是用原始的毫秒级数值做计算,完全不影响原有矩形的坐标运算,只有在渲染刻度标签的时候,才会把对应位置的数值动态转为可读的日期时间字符串。如果需要显示毫秒级精度,只需要把strftime的格式改为'%H:%M:%S.%f'[:-3]即可。

内容的提问来源于stack exchange,提问作者Pavel Komarov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 14:27:04