Matplotlib用时间戳标记x轴,以微秒为单位删除多余的0

时间:2018-11-30 21:21:58

标签: python matplotlib timestamp

我正在绘制几秒钟,并有时间作为x轴上的标签。这是我可以获得正确时间戳的唯一方法。但是,最后会有一堆零。知道如何摆脱它们吗?

plt.style.use('seaborn-whitegrid')
df['timestamp'] = pd.to_datetime(df['timestamp'])
fig, ax = plt.subplots(figsize=(8,4))
seconds=MicrosecondLocator(interval=500000)
myFmt = DateFormatter("%S:%f")
ax.plot(df['timestamp'], df['vibration(g)_0'],  c='blue')
ax.xaxis.set_major_locator(seconds)
ax.xaxis.set_major_formatter(myFmt)

plt.gcf().autofmt_xdate()
plt.show()

这将产生此图像。除了所有额外的零外,其他所有内容看起来都很完美。我如何在保持5个不变的情况下摆脱它们?

enter image description here

1 个答案:

答案 0 :(得分:0)

我想您可能想简单地从字符串中切出最后5位数字。这也是对python datetime: Round/trim number of digits in microseconds的答案。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import MicrosecondLocator, DateFormatter
from matplotlib.ticker import FuncFormatter

x = np.datetime64("2018-11-30T00:00") + np.arange(1,4, dtype="timedelta64[s]")

fig, ax = plt.subplots(figsize=(8,4))
seconds=MicrosecondLocator(interval=500000)
myFmt = DateFormatter("%S:%f")
ax.plot(x,[2,1,3])

def trunc_ms_fmt(x, pos=None):
    return myFmt(x,pos)[:-5]

ax.xaxis.set_major_locator(seconds)
ax.xaxis.set_major_formatter(FuncFormatter(trunc_ms_fmt))

plt.gcf().autofmt_xdate()
plt.show()

enter image description here

请注意,这种格式非常不常见;因此,请确保情节的读者能够理解。