【问题标题】:How to get only HMS formatting in x-axis pandas (matplotlib) plot如何在 x 轴熊猫(matplotlib)图中仅获取 HMS 格式
【发布时间】:2015-01-11 16:14:53
【问题描述】:

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

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)。如何删除 x 轴中的“0 天”前缀?另外,是否有更简单的 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) 

【问题讨论】:

    标签: datetime matplotlib pandas axis-labels timedelta


    【解决方案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]
    

    【讨论】:

    • 感谢@HYRY 这对我有用!我必须添加 ax = plt.gca() (需要添加一行来定义 ax。)
    【解决方案2】:

    试试

    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
    

    【讨论】:

    • 感谢您的建议,但我得到 'Figure' object has no attribute 'autofmtxdate' 错误。感谢@user1324362 快速优雅地解决了)
    • 你必须在 import 语句中添加 import matplotlib.pyplot as plt。
    • 感谢@KirubaharanJ 的回复,但如果我导入 matplotlib.pyplot,我仍然会收到相同的错误“Figure”对象没有属性“autofmtxdata”
    • 对不起,你必须使用 fig.autofmt_xdate(rotation=90),我更正了我的答案
    猜你喜欢
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 2013-10-24
    • 2015-11-21
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多