【问题标题】:How to plot timestamps in python using matplotlib?如何使用 matplotlib 在 python 中绘制时间戳?
【发布时间】:2015-12-20 02:24:49
【问题描述】:

我一直在整个谷歌上搜索这个,但看起来我无法找到我正在寻找的东西。

所以,基本上,我有两个列表:一个列表包含时间戳数据,第二个列表包含对应的值。

现在我的问题是:我的时间戳采用以下格式

['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 方法来绘制它?

【问题讨论】:

  • @kar 正如您已经发现的那样,Google 搜索并不是毫无疑问可以相信的众神之神。只是为了好玩,输入 fed chair(不带引号,不带自动完成建议),然后在您点击 [ENTER] 之后,猜猜您认为最伟大的 AI 是什么——您阅读了 @ 987654331@ 并查看 大胡子 Ben 照片。这就是我们对 Google 搜索结果的信念。

标签: python datetime matplotlib plot


【解决方案1】:

是的,使用 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()

【讨论】:

  • 感谢达里尔的帮助。它对我来说非常有用。但问题是,如果我使用 fig.show() 图表就会瞬间消失。它应该留在屏幕上。不确定我是否在这里遗漏了什么
【解决方案2】:

嗯,一个两步的故事 让他们的情节真的很好

第 1 步:从 stringdatetime 实例
第 2 步 :从 datetimematplotlib 约定兼容 float 日期/时间


像往常一样,devil被隐藏得很详细。

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'
                                            )

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

【讨论】:

  • 你的第一张图表很漂亮!你有它的代码参考吗?
  • 很高兴您受到内置美感的启发。是的,我也很喜欢这个“真理之光”。该代码不在开源域中,因为有一些与 NDA 相关的 dMM()-insights。它不需要超过大约 6000 个 SLOC,所以它是非常可行的。 StackOverfow 内联中缺少 VRML97 支持,否则将能够使用 TURN 和 ZOOM 以交互方式检查 3D 场景图。 对于所有定量数据呈现来说,这确实是一次激动人心的体验,一旦您开始感受图表,就好像握在手中一样探索字面意思!
猜你喜欢
  • 2023-04-05
  • 2016-01-14
  • 2010-12-07
  • 1970-01-01
  • 1970-01-01
  • 2017-02-19
  • 1970-01-01
  • 2013-07-16
  • 1970-01-01
相关资源
最近更新 更多