gpt4 book ai didi

python - 使用时间索引时 pandas 中的 xtick 标签格式

转载 作者:太空宇宙 更新时间:2023-11-03 14:13:36 26 4
gpt4 key购买 nike

我正在 pandas 中绘制时间序列,索引是时间类型(意味着它不包含日期信息)。我想要做的是格式化 xtick 标签以仅显示小时而不是分钟和秒。

import datetime
import random
import pandas as pd
from matplotlib import pylab as plt
%matplotlib inline

#generate a list of random datetime.times
random_time = lambda: (datetime.datetime.strptime("00:00:00", '%H:%M:%S') + datetime.timedelta(minutes=random.randrange(1440))).time()
times = [random_time() for x in range(20)]

#create data frame
df = pd.DataFrame({'times': times, 'counts': [random.randrange(10) for x in range(len(times))]})
df.set_index('times', inplace=True)

df.plot()
#I want tick labels at sensible places, only two here as illustration
custom_tick_locs = [datetime.time(hour=8), datetime.time(hour=16)]
plt.xticks(custom_tick_locs)

产生以下情节:

enter image description here

我的问题是:如何格式化 xtick 标签以仅显示小时? (或者一般的任何其他格式?)

我知道使用日期时间(包括时间和时间)会使事情变得容易得多。但是,由于我要叠加几天的数据,所以我只使用时间。显然,可能有一种方法可以进行叠加(这样一整天下午 1 点都处于相同的 x 位置)所以如果我缺少一个简单的解决方案,请告诉我。

最佳答案

使用 strftime 计算标签并将它们与刻度位置一起传递给 plt.xticks:

custom_tick_locs = [datetime.time(hour=8), datetime.time(hour=16)]
custom_tick_labels = map(lambda x: x.strftime('%H'), custom_tick_locs)
plt.xticks(custom_tick_locs, custom_tick_labels)

关于python - 使用时间索引时 pandas 中的 xtick 标签格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35152621/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com