【问题标题】:Matplotlib ignoring timezoneMatplotlib 忽略时区
【发布时间】:2014-09-03 23:03:56
【问题描述】:

下面的情节

import matplotlib
f= plt.figure(figsize=(12,4))
ax = f.add_subplot(111)
df.set_index('timestamp')['values'].plot(ax=ax)
ax.xaxis.set_major_locator(matplotlib.dates.HourLocator(interval=1))
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%I'))
plt.show()

即使我有,也会在错误的区域 (GMT) 中显示小时:

> df['timestamp'][0]
Timestamp('2014-09-02 18:37:00-0400', tz='US/Eastern')

事实上,如果我注释掉这一行:

ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%I'))

小时在正确的时区呈现。

为什么?

【问题讨论】:

  • 或许可以试试ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%I', 'US/Eastern')
  • @mixedmath 我刚刚尝试过,它使我的安装崩溃(所有软件包的最新版本和带有 conda 的 Python 3)-

标签: python matplotlib


【解决方案1】:

我认为您可以通过在rcParams 中设置时区来获得所需的功能:

import matplotlib
matplotlib.rcParams['timezone'] = 'US/Eastern'

格式化程序可以识别时区,并将时间戳转换为您的 rcParams 时区(可能是 UTC),而如果您不对其进行格式化,它只会获取时间戳并忽略时区。如果我理解正确的话。

更多阅读:

【讨论】:

  • 天哪,这很难找到。问题:如果您使用mdates.DateFormatter,那么它绝对会忽略plot_datexaxis_date 设置的时区以及您使用的任何内容,除非您使用其上的tz 参数
  • 在挖掘了documentation for rrulewrapper(由定位器使用)并看到 rrule 不能很好地适应时区 - 尤其是 pytz 时区 后,最终来到了这里。以后一直处理时区仍然非常令人沮丧。
【解决方案2】:

如果您不想更改 rcParams(这似乎很容易解决),那么您可以将时区传递给 mdates.DateFormatter

from dateutil import tz
mdates.DateFormatter('%H:%M', tz=tz.gettz('Europe/Berlin'))

问题在于mdates.DateFormatter 完全忽略了您设置的所有内容,例如plot_datexaxis_date 或您使用的任何内容。

【讨论】:

    【解决方案3】:

    使用pytz

    import pytz
    import matplotlib.dates as mdates
    
    my_tz = pytz.timezone('Europe/Berlin')
    formatter = mdates.DateFormatter('%m-%d %H:%M', tz=my_tz)
    

    【讨论】:

      猜你喜欢
      • 2020-11-07
      • 2011-10-04
      • 2014-02-03
      • 1970-01-01
      • 2023-03-08
      • 2012-08-06
      • 1970-01-01
      • 2021-03-29
      • 1970-01-01
      相关资源
      最近更新 更多