我一直在整个谷歌上搜索这个问题,但看起来我无法准确找到我要找的东西。
所以,基本上,我有两个列表:一个列表由时间戳数据组成,第二个列表由与其对应的值组成。
现在我的问题是:我的时间戳采用以下格式
['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
方法来绘制它?
是的,使用 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()
第 1 步:从
string
到 datetime
实例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'
)
#------------------------------------------------------------------