gpt4 book ai didi

在 matplotlib/gnuplot 中绘制标记区间

转载 作者:行者123 更新时间:2023-12-03 11:41:35 25 4
gpt4 key购买 nike

我有一个如下所示的数据样本:

a 10:15:22 10:15:30 OK
b 10:15:23 10:15:28 OK
c 10:16:00 10:17:10 FAILED
b 10:16:30 10:16:50 OK

我想要的是按以下方式绘制上述数据:
captions ^
|
c | *------*
b | *---* *--*
a | *--*
|___________________
time >

线条的颜色取决于 OK/FAILED数据点的状态。标签 ( a/b/c/... ) 可以重复也可以不重复。

正如我从 的文档中收集到的那样gnuplot matplotlib ,这种类型的图在后者中应该更容易做,因为它不是标准图并且需要一些预处理。

问题是:
  • 是否有标准方法可以在任何工具中进行这样的绘图?
  • 如果没有,我应该如何绘制这些数据(指向相关工具/文档/函数/示例的指针,这些工具/文档/函数/示例执行的操作有点类似于此处描述的内容)?
  • 最佳答案

    更新:现在包括处理数据样本并使用 mpl 日期功能。

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

    ### The example data
    a=StringIO("""a 10:15:22 10:15:30 OK
    b 10:15:23 10:15:28 OK
    c 10:16:00 10:17:10 FAILED
    b 10:16:30 10:16:50 OK
    """)

    #Converts str into a datetime object.
    conv = lambda s: dt.datetime.strptime(s, '%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'] == 'OK')
    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.03, y-0.03, color, lw=2)
    plt.vlines(xstop, y+0.03, y-0.03, 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('%H:%M:%S')
    ax.xaxis.set_major_formatter(myFmt)
    ax.xaxis.set_major_locator(SecondLocator(interval=20)) # 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.show()

    Resulting image

    关于在 matplotlib/gnuplot 中绘制标记区间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7684475/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com