簡體   English   中英

Python中如何使用datetime.time轉plot

[英]How to use datetime.time to plot in Python

我有 HH:MM:SS 格式的時間戳列表,並希望使用 datetime.time 對某些值進行 plot。 好像 python 不喜歡我這樣做的方式。 有人可以幫忙嗎?

import datetime
import matplotlib.pyplot as plt

# random data
x = [datetime.time(12,10,10), datetime.time(12, 11, 10)]
y = [1,5]

# plot
plt.plot(x,y)
plt.show()

*TypeError: float() argument must be a string or a number*

嗯,一個兩步走的故事讓他們 PLOT 真的很好

在此處輸入圖片說明

步驟1 :將數據准備成正確的格式

datetime到日期/時間的matplotlib約定兼容float


像往常一樣,魔鬼隱藏在細節中。

matplotlib日期幾乎相等,但相等:

#  mPlotDATEs.date2num.__doc__
#                  
#     *d* is either a class `datetime` instance or a sequence of datetimes.
#
#     Return value is a floating point number (or sequence of floats)
#     which gives the number of days (fraction part represents hours,
#     minutes, seconds) since 0001-01-01 00:00:00 UTC, *plus* *one*.
#     The addition of one here is a historical artifact.  Also, note
#     that the Gregorian calendar is assumed; this is not universal
#     practice.  For details, see the module docstring.

所以,強烈建議重新使用他們的“自己的”工具:

from matplotlib import dates as mPlotDATEs   # helper functions num2date()
#                                            #              and date2num()
#                                            #              to convert to/from.

第 2 步:將軸標簽、格式和比例(最小/最大)作為下一個問題進行管理

matplotlib也為這部分帶來了武器。

檢查此答案中的代碼以了解所有詳細信息

它在 Python 3.5.3 和 Matplotlib 2.1.0 中仍然是有效的問題。

一種解決方法是使用datetime.datetime對象,而不是datetime.time的:

import datetime
import matplotlib.pyplot as plt

# random data
x = [datetime.time(12,10,10), datetime.time(12, 11, 10)]
x_dt = [datetime.datetime.combine(datetime.date.today(), t) for t in x]
y = [1,5]

# plot
plt.plot(x_dt, y)
plt.show()

在此處輸入圖片說明

默認日期部分不應該是可見的。 否則,您始終可以使用 DateFormatter:

import matplotlib.dates as mdates
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H-%M-%S'))

我來到這個頁面是因為我有類似的問題。 我有一個 Pandas DataFrame df有一個datetime時間列df.dtm和一個數據列df.x ,跨越幾天,但我想 plot 他們使用matplotlib.pyplot作為 function一天中的時間(日期時間,不是日期和時間日期時間索引)。 即,我希望所有數據點都折疊到 plot 中相同的 24 小時范圍內。我可以毫無問題地比較 plot df.xdf.dtm ,但我剛剛花了兩個小時試圖弄清楚如何轉換df.dtmdf.time (包含一天中沒有日期的時間)然后繪制它。 (對我而言)直接的解決方案不起作用

    df.dtm = pd.to_datetime(df.dtm)
    ax.plot(df.dtm,  df.x)
    # Works  (with times on different dates; a range >24h)

    df['time'] = df.dtm.dt.time
    ax.plot(df.time,  df.x)
    # DOES NOT WORK: ConversionError('Failed to convert value(s) to axis '
    matplotlib.units.ConversionError: Failed to convert value(s) to axis units:
    array([datetime.time(0, 0), datetime.time(0, 5), etc.])

確實有效

    pd.plotting.register_matplotlib_converters()  # Needed to plot Pandas df with Matplotlib
    df.dtm = pd.to_datetime(df.dtm, utc=True)     # NOTE: MUST add a timezone, even if undesired
    ax.plot(df.dtm,  df.x)
    # Works as before
    
    df['time'] = df.dtm.dt.time
    ax.plot(df.time,  df.x)
    # WORKS!!! (with time of day, all data in the same 24h range)

請注意,區別在於前兩行。 第一行允許 Pandas 和 Matplotlib 之間更好的協作,第二行似乎是多余的(甚至是錯誤的),但這對我來說並不重要,因為我使用單個時區並且沒有繪制它。

暫無
暫無

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

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