这是我的示例代码:
import sys
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.dates as md
import pymysql
import numpy as np
import datetime as dt
import matplotlib.ticker as ticker
import pylab as pl
t=[4100,4105,4100,4105,4100,4105,4100,4105,4100,4105,4100,4105]
s=[dt.datetime.now(),dt.datetime.now()+dt.timedelta(seconds=1),dt.datetime.now()+dt.timedelta(seconds=2),dt.datetime.now()+dt.timedelta(seconds=3),
dt.datetime.now()+dt.timedelta(seconds=4),
dt.datetime.now()+dt.timedelta(seconds=5),
dt.datetime.now()+dt.timedelta(seconds=6),
dt.datetime.now()+dt.timedelta(seconds=7),
dt.datetime.now()+dt.timedelta(seconds=8),
dt.datetime.now()+dt.timedelta(seconds=9),
dt.datetime.now()+dt.timedelta(seconds=10),
dt.datetime.now()+dt.timedelta(minutes=1)]
N = len(s)
ind = np.arange(N) # the evenly spaced plot indices
def format_date(x, pos=None):
thisind = np.clip(int(x+0.5), 0, N-1)
return pl.num2date(x).strftime('%Y-%m-%d %H:%M:%S')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(s, t)
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
fig.autofmt_xdate()
plt.show()
请注意最后一个datetime元素是
dt.datetime.now()+dt.timedelta(minutes=1)
这意味着x
轴在最后一个元素和上一个元素之间不连续,此时间范围没有数据。
当我看到上面代码绘制的图形时,结果图像就像w
字符,除了最后一个元素,因为它的时间间隔与其他元素不同,所以它与上一个元素相距很远。 / p>
但是我真正需要的是:跳过x轴的空时间范围,并让最后一个元素在x轴上的间隔与其他元素相同,并保持信号正确的时间。
我主要从以下方面学习此代码: https://matplotlib.org/2.1.2/gallery/api/date_index_formatter.html 但是这个例子似乎只处理周末的全天,不能完全跳过时间范围,例如在x轴上跳过1小时20分钟,有人可以告诉我如何完成它吗?谢谢。