如何在Matplotlib中处理时区?

时间:2014-03-07 16:22:39

标签: python matplotlib plot timezone python-datetime

我的数据点的横坐标是带有时区的datetime.datetime个对象(他们的tzinfo恰好是通过MongoDB获得的bson.tz_util.FixedOffset

当我用scatter()绘制它们时,刻度标签的时区是什么?

更改timezone中的matplotlibrc并不会改变显示的图表中的任何内容(我必须误解Matplotlib文档中的discussion on time zones)。

我使用plot()(而非scatter())进行了一些实验。给定一个日期时,它会绘制它并忽略时区。但是,当给定多个日期时,它使用固定的时区,但是如何确定?我在文档中找不到任何内容。

最后,plot_date()应该是解决这些时区问题的解决方案吗?

2 个答案:

答案 0 :(得分:6)

这个问题已经在评论中得到了回答。但是我自己仍然在与时区挣扎。为了清楚起见,我尝试了所有组合。我认为你有两种主要的方法,取决于你的日期时间对象是否已经在所需的时区或在不同的时区,我试着在下面描述它们。可能我仍然错过/混合了一些东西......

时间戳(日期时间对象):UTC中的 所需显示:在特定时区

  • xaxis_date()设置为您想要的显示时区(默认为rcParam['timezone'],这对我来说是UTC)

时间戳(日期时间对象):特定时区内的 所需显示:在不同的特定时区

  • 使用相应的时区(tzinfo=
  • 输入您的绘图功能日期时间对象
  • 将rcParams ['时区']设置为所需的显示时区
  • 使用dateformatter(即使您对格式the formatter is timezone aware
  • 感到满意

如果您正在使用plot_date(),您也可以传入tz关键字,但对于散点图,这是不可能的。

当您的源数据包含unix时间戳时,如果您要使用matplotlib时区功能,请务必从datetime.datetime.utcfromtimestamp()明智地选择,而不要使用utc:fromtimestamp()

这是我做的实验(在这个案例中是散点()),它可能有点难以理解,但只是写在这里给任何关心的人。注意在时间出现的第一个点(x轴不会在每个子图的同一时间开始): Different combinations of timezones

源码:

import time,datetime,matplotlib
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
from dateutil import tz


#y
data = np.array([i for i in range(24)]) 

#create a datetime object from the unix timestamp 0 (epoch=0:00 1 jan 1970 UTC)
start = datetime.datetime.fromtimestamp(0)  
# it will be the local datetime (depending on your system timezone) 
# corresponding to the epoch
# and it will not have a timezone defined (standard python behaviour)

# if your data comes as unix timestamps and you are going to work with
# matploblib timezone conversions, you better use this function:
start = datetime.datetime.utcfromtimestamp(0)   

timestamps = np.array([start + datetime.timedelta(hours=i) for i in range(24)])
# now add a timezone to those timestamps, US/Pacific UTC -8, be aware this
# will not create the same set of times, they do not coincide
timestamps_tz = np.array([
    start.replace(tzinfo=tz.gettz('US/Pacific')) + datetime.timedelta(hours=i)
    for i in range(24)])


fig = plt.figure(figsize=(10.0, 15.0))


#now plot all variations
plt.subplot(711)
plt.scatter(timestamps, data)
plt.gca().set_xlim([datetime.datetime(1970,1,1), datetime.datetime(1970,1,2,12)])
plt.gca().set_title("1 - tzinfo NO, xaxis_date = NO, formatter=NO")


plt.subplot(712)
plt.scatter(timestamps_tz, data)
plt.gca().set_xlim([datetime.datetime(1970,1,1), datetime.datetime(1970,1,2,12)])
plt.gca().set_title("2 - tzinfo YES, xaxis_date = NO, formatter=NO")


plt.subplot(713)
plt.scatter(timestamps, data)
plt.gca().set_xlim([datetime.datetime(1970,1,1), datetime.datetime(1970,1,2,12)])
plt.gca().xaxis_date('US/Pacific')
plt.gca().set_title("3 - tzinfo NO, xaxis_date = YES, formatter=NO")


plt.subplot(714)
plt.scatter(timestamps, data)
plt.gca().set_xlim([datetime.datetime(1970,1,1), datetime.datetime(1970,1,2,12)])
plt.gca().xaxis_date('US/Pacific')
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M(%d)'))
plt.gca().set_title("4 - tzinfo NO, xaxis_date = YES, formatter=YES")


plt.subplot(715)
plt.scatter(timestamps_tz, data)
plt.gca().set_xlim([datetime.datetime(1970,1,1), datetime.datetime(1970,1,2,12)])
plt.gca().xaxis_date('US/Pacific')
plt.gca().set_title("5 - tzinfo YES, xaxis_date = YES, formatter=NO")


plt.subplot(716)
plt.scatter(timestamps_tz, data)
plt.gca().set_xlim([datetime.datetime(1970,1,1), datetime.datetime(1970,1,2,12)])
plt.gca().set_title("6 - tzinfo YES, xaxis_date = NO, formatter=YES")
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M(%d)'))


plt.subplot(717)
plt.scatter(timestamps_tz, data)
plt.gca().set_xlim([datetime.datetime(1970,1,1), datetime.datetime(1970,1,2,12)])
plt.gca().xaxis_date('US/Pacific')
plt.gca().set_title("7 - tzinfo YES, xaxis_date = YES, formatter=YES")
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M(%d)'))

fig.tight_layout(pad=4)
plt.subplots_adjust(top=0.90)

plt.suptitle(
    'Matplotlib {} with rcParams["timezone"] = {}, system timezone {}"
    .format(matplotlib.__version__,matplotlib.rcParams["timezone"],time.tzname))

plt.show()

答案 1 :(得分:3)

如果像我一样,您在尝试获取可识别时区的 pandas DataFrame 时遇到了此问题,则@pseyfert的评论中建议使用带有时区的格式化程序钱。这是pandas.plot的示例,显示了从EST到EDT过渡时的一些点:

df = pd.DataFrame(
    dict(y=np.random.normal(size=5)),
    index=pd.DatetimeIndex(
        start='2018-03-11 01:30',
        freq='15min',
        periods=5,
        tz=pytz.timezone('US/Eastern')))

请注意,当我们过渡到夏时制时,时区将如何变化:

> [f'{t:%T %Z}' for t in df.index]
['01:30:00 EST',
 '01:45:00 EST',
 '03:00:00 EDT',
 '03:15:00 EDT',
 '03:30:00 EDT']

现在,将其绘制:

df.plot(style='-o')
formatter = mdates.DateFormatter('%m/%d %T %Z', tz=df.index.tz)
plt.gca().xaxis.set_major_formatter(formatter)
plt.show()

enter image description here


PS

不确定为什么某些日期(EST的日期)看起来像是粗体,但大概是matplotlib的内部结构使标签多次渲染,并且位置改变了一个或两个像素...以下内容确认相同的时间戳多次调用格式化程序:

class Foo(mdates.DateFormatter):
    def __init__(self, *args, **kwargs):
        super(Foo, self).__init__(*args, **kwargs)

    def strftime(self, dt, fmt=None):
        s = super(Foo, self).strftime(dt, fmt=fmt)
        print(f'out={s} for dt={dt}, fmt={fmt}')
        return s

并检查以下内容的输出:

df.plot(style='-o')
formatter = Foo('%F %T %Z', tz=df.index.tz)
plt.gca().xaxis.set_major_formatter(formatter)
plt.show()