matplotlib中标记的间隔

时间:2016-05-11 23:44:05

标签: python matplotlib

我正在引用Plotting labeled intervals in matplotlib/gnuplot上的问题,那里暴露的解决方案的问题是,这对文件中只有一行数据不起作用。这是我正在尝试的代码:

#!/usr/bin/env python
#

import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, MinuteLocator, SecondLocator
import numpy as np
from StringIO import StringIO
import datetime as dt

a=StringIO("""MMEX 2016-01-29T12:38:22 2016-01-29T12:39:03 SUCCESS 
""")

#Converts str into a datetime object.
conv = lambda s: dt.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')

#Use numpy to read the data in. 
data = np.genfromtxt(a, converters={1: conv, 2: conv},
                 names=['caption', 'start', 'stop', 'state'], dtype=None)
cap, start, stop = data['caption'], data['start'], data['stop']

#Check the status, because we paint all lines with the same color 
#together
is_ok = (data['state'] == 'SUCCESS')
not_ok = np.logical_not(is_ok)

#Get unique captions and there indices and the inverse mapping    
captions, unique_idx, caption_inv = np.unique(cap, 1, 1)

#Build y values from the number of unique captions.
y = (caption_inv + 1) / float(len(captions) + 1)

#Plot function
def timelines(y, xstart, xstop, color='b'):
    """Plot timelines at y from xstart to xstop with given color."""   
    plt.hlines(y, xstart, xstop, color, lw=4)
    plt.vlines(xstart, y+0.005, y-0.005, color, lw=2)
    plt.vlines(xstop, y+0.005, y-0.005, color, lw=2)

#Plot ok tl black    
timelines(y[is_ok], start[is_ok], stop[is_ok], 'k')
#Plot fail tl red
timelines(y[not_ok], start[not_ok], stop[not_ok], 'r')

#Setup the plot
ax = plt.gca()
ax.xaxis_date()
myFmt = DateFormatter('%Y-%m-%dT%H:%M:%S')
ax.xaxis.set_major_formatter(myFmt)
ax.xaxis.set_major_locator(SecondLocator(interval=3600)) # used to be         SecondLocator(0, interval=20)

#To adjust the xlimits a timedelta is needed.
delta = (stop.max() - start.min())/10

plt.yticks(y[unique_idx], captions)
plt.ylim(0,1)
plt.xlim(start.min()-delta, stop.max()+delta)
plt.xlabel('Time')
plt.xticks(rotation=70)
plt.show(block=True)

当我尝试此代码时,出现以下错误:

Traceback (most recent call last):
  File "./testPlot.py", line 49, in <module>
    timelines(y[is_ok], start[is_ok], stop[is_ok], 'k')
ValueError: boolean index array should have 1 dimension

另外,当我尝试在数据上添加虚拟线时,让我们说“MMEX 2016-01-01T00:00:00 2016-01-01T00:00:00 SUCCESS”,情节有效,但看起来不看好。

有什么建议吗?当我找到解决方案时,我试图将这个问题放在同一个帖子上,但我没有足够的声誉......

提前致谢

1 个答案:

答案 0 :(得分:0)

问题在于,当您只使用np.genfromtxt读取1个项目时,它会生成标量(0维)。我们需要他们至少1D。

您可以在定义timelines功能的位置上方添加这些行,然后一切正常。

这会使用numpy函数np.atleast_1d()将标量转换为1D numpy数组。

#Check the dimensions are at least 1D (for 1-item data input)
if start.ndim < 1:
    start = np.atleast_1d(start)
if stop.ndim < 1::
    stop = np.atleast_1d(stop)    
if is_ok.ndim < 1:
    is_ok = np.atleast_1d(is_ok)    
if not_ok.ndim < 1:
    not_ok = np.atleast_1d(is_ok)  

输出:

enter image description here