首页 > 解决方案 > 如果在单独的列表中有错误值,有没有办法省略图中的数据点?

问题描述

为了使其尽可能简单,我试图绘制 .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()

谢谢!

标签: pythonpython-3.xnumpymatplotlib

解决方案


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使用虚拟数据的示例是(请注意nor没有值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)

在此处输入图像描述


推荐阅读