简体   繁体   English

在 matplotlib.pyplot 中绘制带有时区的日期

[英]Plotting dates with timezones in matplotlib.pyplot

How do I properly set pyplot to plot dates in a given timezone?如何正确设置 pyplot 以在给定时区绘制日期? I can see various places to put a tzinfo object, but all of these either do nothing or do not remotely work as expected.我可以看到各种放置 tzinfo 对象的地方,但所有这些要么什么都不做,要么不能按预期远程工作。 I load a list of records from a csv, with each record being [naive timestamp in UTC, number to plot]我从 csv 加载记录列表,每条记录都是 [UTC 中的原始时间戳,要绘制的数字]

import pytz
from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
estZone=pytz.timezone('US/Eastern')

records=[['10/10/17 12:00','100'],['11/10/17 12:00','150'],['12/10/17 12:00','200']]

def parseDT(stampString):
    return datetime.strptime(stampString,'%d/%m/%y %H:%M')

def plotGraph():
    xvalues=[]
    yvalues=[]
    for r in records:
        rdatetime=(parseDT(r[0])) #parseDT just returns naive DT
        rdatetime=pytz.utc.localize(rdatetime)
        rdatetime=rdatetime.astimezone(tz=estZone)
        xvalues.append(rdatetime)
        yvalues.append(int(r[1]))

    fig,ax=plt.subplots(figsize=(8,3))
    plt.plot_date(xvalues,yvalues,ls='solid',lw=1.5,aa=True,marker='None',color='g')
    dayFmt=mdates.DateFormatter('%a-%b-%d')
    hrFmt=mdates.DateFormatter('%H:00')
    ax.xaxis.set_major_formatter(dayFmt)
    ax.xaxis.set_major_locator(mdates.DayLocator())
    ax.xaxis.set_minor_locator(mdates.HourLocator(byhour=[6,12,18]))
    ax.xaxis.set_minor_formatter(hrFmt)
    plt.grid(b=True, which='both',linestyle='dotted')
    plt.show()

plotGraph()

This produces (minus some formatting) this figure:这会产生(减去一些格式)这个数字:

第一个输出 Which is actually still UTC.这实际上仍然是UTC。 It's identical to the result if I had omitted the astimezone(tz=estZone) , even though I've verified that part is definitely functioning.如果我省略了astimezone(tz=estZone) ,它与结果相同,即使我已经验证该部分确实在运行。

If I proceed to pass tz=estZone to plt.plot_date , the figure is identical.如果我继续将tz=estZone传递给plt.plot_date ,则该数字是相同的。 There's no change.没有变化。 How can I change this to make an EST graph from my UTC timestamps?如何更改此设置以根据我的 UTC 时间戳制作 EST 图?

I had tried passing the timezone to the DateFormatters for the x-axis labels before, but the timezone modifier seems to be applied after the locators are placed, leaving all the labels reading 4 hours behind each midnight or the hours specified. 我曾尝试过将时区传递给x轴标签的DateFormatters,但是似乎在放置定位器后应用了时区修饰符,使所有标签在每个午夜或指定的小时之后落后4个小时。 I've realized that the locators also need the timezone as a parameter to counteract this. 我已经意识到定位器还需要时区作为参数来抵消这种情况。 That'd do it. 那样做。

I've been going through this for the past hour as well: the source data had the correct timezone, but Matplotlib was ignoring it.过去一个小时我也一直在经历这个:源数据有正确的时区,但 Matplotlib 忽略了它。 The fix is passing the timezone to the locators and formatters.解决方法是将时区传递给定位器格式化程序。

Example code to clarify:示例代码澄清:

plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=1, tz=local_tz))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y', tz=local_tz))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM