0

I am plotting over a period of seconds and have time as the labels on the x-axis. Here is the only way I could get the correct time stamps. However, there are a bunch of zeros on the end. Any idea how to get rid of them??

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()

This produces this image. Everything looks perfect except for all of the extra zeros. How can I get rid of them while still keeping the 5?

enter image description here

Dana McDowelle
  • 269
  • 1
  • 6
  • 13

1 Answers1

0

I guess you would want to simply cut the last 5 digits out of the string. That's also what answers to python datetime: Round/trim number of digits in microseconds suggest.

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

Note that this format is quite unusual; so make sure the reader of the plot understands it.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712