Matplotlib:交互式Jupyter图中基于日期时间的线集合

时间:2019-03-12 15:37:26

标签: python matplotlib jupyter-notebook

我正在尝试在Jupyter笔记本的matplotlib交互式图中绘制成千上万的线段的集合。我的问题是

  • x值是日期时间(datetime64 [ns],基本上是POSIX时间戳)
  • LineCollection只能基于数字
  • 当将图的x轴保留为数字时,缩放图时,x轴会根据缩放比例很好地调整比例。但是,x轴的值无用。将x轴格式化为可参考的日期时间值时,缩放时会丢失此信息。

示例:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import collections  as mc
import matplotlib.dates as mdates

%matplotlib nbagg # interactive plot in jupyter notebook

x = np.array([['2018-03-19T07:01:00.000073810', '2018-03-19T07:01:00.632164618'],
       ['2018-03-19T07:01:00.000073811', '2018-03-19T07:01:00.742295898'],
       ['2018-03-19T07:01:00.218747698', '2018-03-19T07:01:00.260067814'],
      ['2018-03-19T07:01:01.218747698', '2018-03-19T07:01:02.260067814'],
      ['2018-03-19T07:01:02.218747698', '2018-03-19T07:01:02.260067814'],
      ['2018-03-19T07:01:02.218747698', '2018-03-19T07:01:02.260067814']],
      dtype='datetime64[ns]')
y = np.array([[12355.5, 12355.5],
       [12363. , 12363. ],
       [12362.5, 12362.5],
       [12355.5, 12355.5],
       [12363. , 12363. ],
       [12362.5, 12362.5]])

fig, ax = plt.subplots()
segs = np.zeros((x.shape[0], x.shape[1], 2))
segs[:, :, 1] = y
segs[:, :, 0] = mdates.date2num(x)
lc = mc.LineCollection(segs)
ax.set_xlim(segs[:,:,0].min(), segs[:,:,0].max())
ax.set_ylim(segs[:,:,1].min()-1, segs[:,:,1].max()+1)
ax.add_collection(lc)

现在,缩放效果很好-x轴比例随缩放进行调整-但x轴值没有告诉我任何有用的信息,即我当前正在查看的准确时间。为了解决这个问题,我尝试例如做

ax.xaxis.set_major_locator(mdates.SecondLocator())
#ax.xaxis.set_minor_locator(mdates.MicrosecondLocator()) # this causes the plot not to display
Fmt = mdates.DateFormatter("%S")
ax.xaxis.set_major_formatter(Fmt)

现在明显地缩放无法正常工作,因为matplotlib不知道更精细的刻度线的格式。因此,如果我进行足够的缩放(这是我需要做的),则我在x轴上基本上没有刻度。

有没有办法解决这个问题?我能想到的一种方法是能够设置在图缩放时调用的回调,并调整x轴的格式。但据我所知,这是不可能的。

0 个答案:

没有答案