【问题标题】:Adding UTC time axis to plot with local time in time format添加 UTC 时间轴以使用时间格式绘制本地时间
【发布时间】:2017-01-19 04:59:11
【问题描述】:

我有一个看起来像这样的 DataFrame 图

绘制的DataFrame上的索引如下

In[102]: res.index
Out[102]: 
Index([00:00:00, 00:05:00, 00:10:00, 00:15:00, 00:20:00, 00:25:00, 00:30:00,
       00:35:00, 00:40:00, 00:45:00,
       ...
       23:10:00, 23:15:00, 23:20:00, 23:25:00, 23:30:00, 23:35:00, 23:40:00,
       23:45:00, 23:50:00, 23:55:00],
      dtype='object', name='time', length=288)

x 轴上描绘的时间是中部标准时间,我想在绘图顶部添加一个辅助 x 轴以及相应的 UTC 时间。我知道这将使数字变为6:00 ... 22:00 ... 4:00,但这很好。 我该怎么做


我的尝试

我知道可以使用以下命令创建第二个 x 轴,并且我设法使用以下命令从第一个 x 轴获取看起来像 xticks 的内容 - 我的下一步将是尝试确定如何将这些时间转移到 UTC - 我仍然不确定想法。

ax2 = ax.twiny()
ax2.set_xlabel('UTC time')
local_ticks = ax.get_xticks().tolist()

然而,在绘制这个基本步骤时,我发现get_xticks() 比原始 x 轴产生了一个额外的刻度,因此它们没有对齐。

相应地,将这些视为秒并尝试执行一些进一步的操作以达到秒->CST->UTC 仍然会给我留下丑陋的缩放“双白线”在每个滴答声。理想情况下,我希望 完全相同 沿辅助 x 轴刻度,除非带有适当标记的 UTC 时间。


样本生成

如果你想生成一个像我提供的第一个情节一样的情节,我把它放在一起。

import datetime

import numpy as np
import random
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
start_date = datetime.datetime(2016, 9, 5)
end_date = datetime.datetime.now()

dts = []
cur_date = start_date 
while cur_date < end_date:
    dts.append((cur_date, np.random.uniform(low=0.0, high=12.0)))
    cur_date += datetime.timedelta(minutes=np.random.uniform(10, 20))
dts = pd.DataFrame(dts, columns=['timestamp', 'lag'])
dts.index = dts.timestamp
dts.drop('timestamp', axis=1, inplace=True)

cur_time = datetime.datetime(1, 1, 1, 0, 0)
aggs = []
while cur_time < datetime.datetime(1, 1, 1, 23, 59, 0):
    aggs.append((cur_time.time(), 
                dts.between_time(cur_time.time(),
                (cur_time + datetime.timedelta(minutes=5)).time(), 
                include_end=False)['lag'].mean()))
    cur_time += datetime.timedelta(minutes=5)

res = pd.DataFrame(aggs, columns = ['time', 'lag'])
res.index = res.time
res.drop('time', axis=1, inplace=True)

ax = res.plot(figsize=(15, 10))

【问题讨论】:

    标签: python pandas matplotlib plot


    【解决方案1】:

    我通过显式设置 x 轴刻度标签而不是让 matplotlib 决定来让它工作。这可以通过以下方式完成:

    ax.set_xticks([2*60*60*i for i in range(0,13)])

    这还有一个额外的好处是列出的时间不是随机的;您可以将增量设置为 1 小时、2 小时、... 在上面的 sn-p 中,2* 部分表示 2 小时的增量。

    然后,在其余代码中,您需要将轴复制到 ax2,并手动设置标签。我是这样做的:

    # Begin solution
    
    ax.set_xticks([2*60*60*i for i in range(0,13)])
    
    local_ticks = ax.get_xticks().tolist()
    labels = [str(datetime.timedelta(seconds=(second+6*60*60))) for second in local_ticks]
    
    ax2 = ax.twiny()
    plt.sca(ax2)
    ax2.set_xlabel('UTC time')
    plt.xticks(local_ticks, labels)
    

    这是最终的图像:

    可以通过字符串解析手动更改上述轴中的“1天”部分。

    实际上,最简单的解决方法是简单地添加ax2.set_xticks(ax.get_xticks())。我认为问题在于您没有明确说明轴 1 的 xticks,但您为轴 2 说明了;在创建绘图时,已重新计算 xticks,而轴 2 的 xticks 保持不变。

    【讨论】:

      猜你喜欢
      • 2015-06-03
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 2013-08-26
      • 2018-05-08
      • 2012-02-22
      • 2018-07-02
      • 2018-08-10
      相关资源
      最近更新 更多