繁体   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