如何在x轴pandas(matplotlib)图中仅获取HMS格式

时间:2014-11-14 09:51:40

标签: datetime matplotlib pandas axis-labels timedelta

我试图绘制几个小时内的温度测量值。我的数据文件包含以毫秒为单位的时间。

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

我得到的图表的x轴范围为" 0天00:00:00"到" 0天01:14:11"。 我想截断这个只显示HH:MM:SS(例如00:00:00到1:14:11)。如何删除" 0天" x轴前缀?另外,是否有更简单的pd命令将数据转换为HMS对象? 谢谢你的帮助!

编辑:感谢@HYRY,这是我的最终代码

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 个答案:

答案 0 :(得分:1)

尝试

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

答案 1 :(得分:1)

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]