How to get only HMS formatting in x-axis pandas (matplotlib) plot

1.7k views Asked by At

I'm trying to plot temperature measurements taken over a few hours. My data file contains the time in milliseconds.

from datetime import timedelta
from pandas import to_timedelta
import pandas as pd
import datetime DT
df = pd.read_csv('temperature_measurements.txt')
my_columns=['time_ms','tempC','humidity']
df.columns = my_columns

#remove timestamp offset
startTime = df['time_ms'].min()
#get time in seconds, round off because I was getting >2 significant figuress
df['time_s']=np.round((df['time_ms']-startTime)/1000)

#convert to datetime object
df['time']=pd.to_timedelta((df['time_s']),unit='s')
df.plot(x='time',y='tempC')

I get a plot where the x axis ranges from "0 days 00:00:00" to "0 days 01:14:11". I want to truncate this to show only HH:MM:SS (e.g. 00:00:00 to 1:14:11). How can I remove the "0 days" prefix in the x-axis? Also, is there a simpler pd command to convert data to HMS objects? Thanks for your help!

EDIT: Thanks to @HYRY here is my final code

plt.plot(df.time, df.tempC)
ax = plt.gca()
tick_labels = ax.xaxis.major.formatter.seq
ax.xaxis.major.formatter.seq = [label.split()[-1] if label else "" for label in tick_labels]
plt.xticks(rotation=90) 
2

There are 2 answers

1
HYRY On BEST ANSWER

Add following code after df.plot(x='time',y='tempC'):

tick_labels = ax.xaxis.major.formatter.seq
ax.xaxis.major.formatter.seq = [label.split()[-1] if label else "" for label in tick_labels]
4
Kirubaharan J On

Try

import matplotlib.pyplot as plt
fig = plt.figure() # creates matplotlib figure object
plt.plot(df.time, df.tempC) # plots x, y
fig.autofmt_xdate(rotation=90) # rotates the date to 90 degree to make it look better