簡體   English   中英

在繪制以時間增量為索引的熊貓系列時設置x軸的格式

[英]Format x-axis when plotting pandas series with timedeltas as indices

我想繪制一個以timedeltas為索引的熊貓系列,並自定義x-tick格式。 一個最小的例子是:

import pandas as pd
import matplotlib.pyplot as plt
times = ['Wed Feb 20 08:28:04 PST 2019', 'Wed Feb 20 09:29:04 PST 2019', 'Wed Feb 20 10:30:04 PST 2019']
timestamps = [pd.Timestamp(t) for t in times]
timedeltas = [t - timestamps[0] for t in timestamps]
timedeltas
ts = pd.Series([1, 2, 5], index=timedeltas)
ts.plot()
plt.savefig("/tmp/plot.png")`

Which produces the following
[output][1].

我想將時間格式設置為[小時]:[分鍾]。

添加

import matplotlib.dates as mdates
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))

導致以下錯誤:

ValueError: Cannot convert -1000000000000 to a date.  This often happens if non-datetime values are passed to an axis that expects datetime objects.

這里的問題是我們無法格式化時間增量。

@Shawn Chin 在這里有一個很好的解決方案

我已經稍微修改了他的答案,以便在適用的小時和分鍾數中添加前導零,這僅僅是因為我認為它看起來更好。 盡管它也將天數限制為兩位數,但是從您的問題來看,我假設您只想顯示小時和分鍾。

肖恩的稍微編輯的功能:

def strfdelta(tdelta, fmt):
    d = {"days": tdelta.days}
    d["hours"], rem = divmod(tdelta.seconds, 3600)
    d["minutes"], d["seconds"] = divmod(rem, 60)
    for key in d:
        d[key] = "{:02d}".format(d[key])
    return fmt.format(**d)

在您的代碼中添加一行額外的代碼來調用此函數,希望產生的輸出如下:

import pandas as pd
import matplotlib.pyplot as plt
times = ['Wed Feb 20 08:28:04 PST 2019', 'Wed Feb 20 09:29:04 PST 2019', 'Wed Feb 20 10:30:04 PST 2019']
timestamps = [pd.Timestamp(t) for t in times]
timedeltas = [t - timestamps[0] for t in timestamps]
timedeltas = [strfdelta(t, '{hours}:{minutes}') for t in timedeltas]
ts = pd.Series([1, 2, 5], index=timedeltas)
ts.plot()

折線圖輸出

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM