【问题标题】:Is there a way to omit data points in a plot if it has an error value in a separate list?如果在单独的列表中有错误值,有没有办法省略图中的数据点?
【发布时间】:2020-04-12 04:20:39
【问题描述】:

为了使其尽可能简单,我尝试绘制 .DAT 文件中数据的速率与时间的关系。我在 24 小时内每 10 分钟绘制一次点。由于数据文件的格式和我的实现,时间数据是一个字符串列表。

我有一个单独的列表,它为每个速率实例提供了一个错误值。如果错误!= 0,我想从图中省略速率点,但保持 x 轴的时间相同。

到目前为止,我只能想到在 if 语句下面附加速率和时间值列表:

for line in file:
    columns = line.split()

    #throws out all instances of 0 in specified column
    if(int(columns[5]) == 0:

        hhmmss.append(str(columns[1]))
        lv0rate.append(float(columns[3]))
        error.append(int(columns[5]))

但是,这会导致我的 x 轴因错误点而被“挤压”,我希望 x 轴在 24 小时内保持一致。

我在一个 3x3 的子图网格上绘制它,所以我用于设置图形的控制函数如下所示:

# plot
fig, axs = plt.subplots(3, 3)
fig.subplots_adjust(left=0.2, wspace=0.6)
make_plot(axs)

# alignment of axes
fig.align_ylabels(axs[:, 1])

# set the x major locator
for axi in axs.flat:
    axi.xaxis.set_major_locator(plt.MaxNLocator(30))
fig

for axs in fig.axes:
    plt.sca(axs)
    plt.xticks(rotation=70)

plt.rcParams['axes.grid'] = True
plt.show()

谢谢!

【问题讨论】:

    标签: python python-3.x numpy matplotlib


    【解决方案1】:

    x 轴被“压扁”,因为它们是字符串,并且 x 值之间没有距离的概念,您需要将 hhmmss 转换为 datetime 对象:

    import pandas as pd
    
    hhmmss = ['00:00:00', '01:00:00', '02:00:00', '05:00:00']
    hhmmss_time = [pd.Timestamp(time) for time in hhmmss]
    print(hhmmss_time)
    
    # Timestamp('2020-04-12 00:00:00'),
    # Timestamp('2020-04-12 01:00:00'),
    # ...
    

    您可以使用 hhmmss_time 进行绘图,因为它是一个 Timestamp 对象,但正如您所见,它将当前日期分配给时间,但是,您可以使用 matplotlib 中的格式化程序选项仅显示时间信息

    hours = mdates.HourLocator(interval = 1)
    h_fmt = mdates.DateFormatter('%H:%M:%S')
    
    # ...
    
    ax.xaxis.set_major_locator(hours)
    ax.xaxis.set_major_formatter(h_fmt)
    

    使用虚拟数据的示例是(请注意,03:00:00 和 04:00:00 都没有值):

    y = np.linspace(0,3,4)
    fig, ax = plt.subplots()
    
    ax.xaxis.set_major_locator(hours)
    ax.xaxis.set_major_formatter(h_fmt)
    ax.plot(hhmmss_time, y)
    

    【讨论】:

    • 设置 hhmmss_time 时,似乎读错了我的 hhmmss。我的 hhmmss 是一个没有冒号的时间列表,因为它看起来像 [000000, 001000, 002000, ... , 235000]。当我打印时间戳时,它看起来像 Timestamp('19-01-01 00:00:00.000001')。你有什么建议吗?我似乎无法弄清楚
    • 如果您有特定格式,请使用hhmmss_time = [pd.to_datetime(time, format='%H%M%S') for time in hhmmss],时间戳和日期时间对象将始终包含日期部分,这就是您将matplotlib配置为仅显示时间部分的原因。
    • 啊,我知道我执行错了,但你帮我看看我在做什么。非常感谢,成功了!
    猜你喜欢
    • 2020-01-09
    • 2021-10-17
    • 2011-06-12
    • 2018-11-15
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    相关资源
    最近更新 更多