如何使用matplotlib在python中绘制时间戳?

7
我已经在谷歌上全面搜索,但似乎无法找到我要找的东西。
基本上,我有两个列表:一个列表包含时间戳数据,另一个列表包含相应的值。
现在我的问题是:我的时间戳格式如下:
['Mon Sep 1 16:40:20 2015', 'Mon Sep 1 16:45:20 2015',
 'Mon Sep 1 16:50:20 2015', 'Mon Sep 1 16:55:20 2015'] 

那么,在 matplotlib 中使用哪种时间格式?我试图直接绘制,但它给了我:
ValueError: invalid literal 

我能翻译为中文:

我能使用 datetime.datetime.strptime 来转换它吗?如果不能,还有其他的方法吗?

在将 timestamp 转换为正确的格式之后,我应该如何绘制新转换的时间戳和相应的值?

我能使用 matplotlib.pyplot.plot(time, data) 吗,还是必须使用 plot_date 方法来绘制它?


1
请参考以下链接:http://codrspace.com/szeitlin/biking-data-from-xml-to-plots-part-2/ - szeitlin
@kar,正如你已经发现的那样,谷歌搜索并非一个毫无怀疑的神。只是为了好玩,输入 fed chair (不要加引号,也不要使用自动完成建议),在你按下 [ENTER] 键之后,猜猜最伟大的AI认为你会相信什么——你看到了 Janet Yellen 和一张有胡子的Ben的照片。这就是我们对谷歌搜索结果的信仰。 - user3666197
2个回答

8

是的,使用strptime函数。

import datetime
import matplotlib.pyplot as plt

x = ['Mon Sep 1 16:40:20 2015', 'Mon Sep 1 16:45:20 2015',
    'Mon Sep 1 16:50:20 2015', 'Mon Sep 1 16:55:20 2015']
y = range(4)

x = [datetime.datetime.strptime(elem, '%a %b %d %H:%M:%S %Y') for elem in x]

(fig, ax) = plt.subplots(1, 1)
ax.plot(x, y)
fig.show()

enter image description here


感谢Daryl的帮助。对我来说基本上已经解决了问题。但是问题在于,如果我使用fig.show(),图形就会一闪而过。它应该停留在屏幕上。不确定我是否漏掉了什么。 - kar

8

一个两步故事,让PLOT变得非常漂亮

输入图像描述 输入图像描述

步骤1:从string转换为datetime实例
步骤2:从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.

管理轴标签、格式和刻度(最小/最大)是一个单独的问题

尽管如此,matplotlib也为你提供了解决这部分问题的工具:

from matplotlib.dates   import  DateFormatter,    \
                                AutoDateLocator,   \
                                HourLocator,        \
                                MinuteLocator,       \
                                epoch2num
from matplotlib.ticker  import  ScalarFormatter, FuncFormatter

例如,它可能会执行以下操作:

    aPlotAX.set_xlim( x_min, x_MAX )               # X-AXIS LIMITs ------------------------------------------------------------------------------- X-LIMITs

    #lt.gca().xaxis.set_major_locator(      matplotlib.ticker.FixedLocator(  secs ) )
    #lt.gca().xaxis.set_major_formatter(    matplotlib.ticker.FuncFormatter( lambda pos, _: time.strftime( "%d-%m-%Y %H:%M:%S", time.localtime( pos ) ) ) )

    aPlotAX.xaxis.set_major_locator(   AutoDateLocator() )

    aPlotAX.xaxis.set_major_formatter( DateFormatter( '%Y-%m-%d %H:%M' ) )  # ----------------------------------------------------------------------------------------- X-FORMAT

    #--------------------------------------------- # 90-deg x-tick-LABELs

    plt.setp( plt.gca().get_xticklabels(),  rotation            = 90,
                                            horizontalalignment = 'right'
                                            )

    #------------------------------------------------------------------

2
你的第一个图表很漂亮!你有它的代码参考吗? - Abe Hoffman
1
很高兴你被内置美所启发。是的,我也非常喜欢这个“真理之光”。由于涉及到一些NDA相关的dMM()洞见,代码不在开源领域。它只有大约6000行代码,所以做起来相当容易。StackOverfow inlines中缺少VRML97支持,否则您将能够交互式地检查3D场景图,进行旋转和缩放。一旦您开始感受到图形,就像抓住在手中一样,对于所有数量数据呈现来说,这确实是一个激动人心的体验! - user3666197

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接