Home > Blockchain >  How to hide milliseconds when plotting in matplotlib?
How to hide milliseconds when plotting in matplotlib?

Time:06-03

The data I am using has milliseconds resolution, so I can't remove them when plotting.

I have used following code to change from Day of year, hours-minutes-seconds-milliseconds to simply hours-minutes-seconds-milliseconds

df['epoch'] = pd.to_datetime(df.epoch, format='%Y-%m-%dT%H:%M:%S.%f')
df['time'] = df['epoch'].dt.strftime('%H:%M:%S.%f')

For removing milliseconds, I can simply remove f from this line ('%H:%M:%S.%f'), but the plot then doesn't work properly since it has milliseconds steps. So how can I plot with milliseconds, but then hide it from x-axis when plotting?

CodePudding user response:

There are two ways to do this.

First is to resample the data excluding the milliseconds and plot the same way you already are. You can select a period for resample so that you can just decimate the signal and not change it.

EDIT: Perhaps I should not have included this b/c you asked specifically for leaving the ms data in place and simply not to plot it. Skip this part of the answer if you don't want to degrade your signal.

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Create 1 min of synthetic data with ms time resolutions.
ind = pd.date_range(start='2022-01-01T12:00:00', end='2022-01-01T12:00:01', freq='ms')
data = np.random.randint(0, 255, size=ind.shape[0])

df = pd.DataFrame(data={"data": data}, index=ind)

# convert to periodic index
p_ind = df.index.to_period('s')
df.index = p_index
df.plot()

The second method is not to the use the built-in Pandas plotting but create your own figure and axes. This is the only way to control the details of the plot. The Pandas built in is only good for quick and dirty work.

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Create 100 ms of synthetic data with ms time resolutions.
ind = pd.date_range(start='2022-01-01T12:00:00', end='2022-01-01T12:00:00.10', freq='ms')
data = np.random.randint(0, 255, size=ind.shape[0])

df = pd.DataFrame(data={"data": data}, index=ind)


fig, ax = plt.subplots(nrows=1) # the subplots with the 's'
ax.xaxis.set_tick_params(which="major", rotation=45)
ax.plot(df)

You may want more control and it's best to use a tick locator function. I'll leave that up to you to research but it's explained here.

  • Related