python - 如果在单独的列表中有错误值,有没有办法省略图中的数据点?
问题描述
为了使其尽可能简单,我试图绘制 .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()
谢谢!
解决方案
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)
推荐阅读
- sql - Powershell 和 SQL - 必须声明标量变量“@”
- python - 如何使用python将文本文件中的两列提取到csv文件中?
- c# - C#查看插入的数据无需任何按钮即可查看
- arrays - 在没有 array_to_json 的 PostgreSQL 中将记录数组转换为 JSON
- c++ - 根据传入命令选择和执行任务的模式/架构
- react-native - 登录 Instagram 时出错(禁用 Cookie) - React Native WebView
- c# - 如何在 ASP.NET Core 2.0 中为 IHttpcontextAccessor 使用依赖注入
- amazon-web-services - 如何获取本地ec2实例的container-instance-id
- c# - 将命令绑定到动态创建的按钮
- python - 无法在 Jupyter 笔记本中运行 tf.enable_eager_execution()