Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

wrong time and resolution axis when plotting time series (secs instead of min)

I want to plot a DataFrame as a time series

import matplotlib.pyplot as plt
plt.plot(df['time'],df['Power'])

or

df2 = df.set_index('time')
df2.Power.plot()

which both show all 3531 y values correctly but wrong x axis time labels, like 25 seconds instead of 25 minutes.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

timestamps are not completely regular and have ms decimals

0      2022-05-16 19:59:25.690
1      2022-05-16 19:59:25.890
2      2022-05-16 19:59:26.100
3      2022-05-16 19:59:26.320
4      2022-05-16 19:59:26.530
                 ...          
3526   2022-05-16 20:24:51.690
3527   2022-05-16 20:24:52.420
3528   2022-05-16 20:24:52.740
3529   2022-05-16 20:24:53.210
3530   2022-05-16 20:24:54.570

Name: time, Length: 3531, dtype: datetime64[ns]

what am I missing?

>Solution :

You should use matplotlib.dates to set ticks interval and format.
For example you could use:

ax.xaxis.set_major_locator(md.MinuteLocator(interval = 1))

in order to set a tick for each minute and

ax.xaxis.set_major_formatter(md.DateFormatter('%H:%M'))

in order to change tick label format to HOUR:MINUTE.
Eventually, you could also use

plt.setp(ax.xaxis.get_majorticklabels(), rotation = 90)

to rotate tick label by 90 degrees, in order to improve readibility.
You can change above parameters as you please in order to better plot your particoular data.

Complete Code

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


N = 3531
df = pd.DataFrame()
df['time'] = pd.date_range(start = '2022-05-16 19:59:25.69', end = '2022-05-16 20:24:54.570', periods = N)
df['Power'] = np.random.rand(N)

fig, ax = plt.subplots()

ax.plot(df['time'], df['Power'])

ax.xaxis.set_major_locator(md.MinuteLocator(interval = 1))
ax.xaxis.set_major_formatter(md.DateFormatter('%H:%M'))
plt.setp(ax.xaxis.get_majorticklabels(), rotation = 90)

plt.show()

Plot

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading