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

kar*_*kar 4 python plot datetime matplotlib

我一直在整个Google上搜索此内容,但似乎无法完全找到所需的内容。

因此,基本上,我有两个列表:一个列表由时间戳数据组成,第二个列表由与之对应的值组成。

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

['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'] 
Run Code Online (Sandbox Code Playgroud)

那么,哪种时间格式用于matplotlib?我试图画出这个直线,但它给了我:

ValueError: invalid literal 
Run Code Online (Sandbox Code Playgroud)

我可以datetime.datetime.strptime用来转换吗?如果没有,那还有什么其他方法呢?

将转换为timestamp正确的格式后,如何绘制新的转换后的时间戳及其对应的值?

我可以使用matplotlib.pyplot.plot(time, data)还是必须使用plot_date方法进行绘制?

dar*_*ryl 5

是的,使用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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


use*_*197 5

嗯,一个两步走的故事让他们 PLOT 真的很好

在此处输入图片说明 在此处输入图片说明

第 1 步:从 astringdatetime实例
第 2 步:从 adatetimematplotlibfloat日期/时间兼容的约定


像往常一样,魔鬼隐藏在细节中。

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.
Run Code Online (Sandbox Code Playgroud)

所以,强烈建议重新使用他们的“自己的”工具:

from matplotlib import dates as mPlotDATEs   # helper functions num2date()
#                                            #              and date2num()
#                                            #              to convert to/from.
Run Code Online (Sandbox Code Playgroud)

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

尽管如此,matplotlib 也为这部分带来了武器:

from matplotlib.dates   import  DateFormatter,    \
                                AutoDateLocator,   \
                                HourLocator,        \
                                MinuteLocator,       \
                                epoch2num
from matplotlib.ticker  import  ScalarFormatter, FuncFormatter
Run Code Online (Sandbox Code Playgroud)

并且可以例如:

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

    #------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

  • 你的第一个图表很漂亮!你有它的代码参考吗? (2认同)