【问题标题】:How can i plot graph whit 5 minutes time interval如何以 5 分钟的时间间隔绘制图表
【发布时间】:2026-01-14 07:55:02
【问题描述】:

我在 python 中绘制图形时遇到问题。 我有一个.json 文件。我必须从这个文件中读取“时间”。 程序可以从文件中读取每个“时间”,我将所有这些都添加到列表中。 我想以 5 分钟的间隔绘制图表。然后我选择了以 00 或 05 结尾的列表中的时间,然后添加到另一个列表中。 顺便说一句,我的 list2 有这样的对象“2015-1-03 1:15:00” 我的 list1 有 20 等整数。

最后,当我尝试使用该代码绘制图表时:

plt.figure(2)
plt.plot(range(len(pd1)), list1)
plt.xticks(range(len(grapdict)), list2, rotation=25)
pl.show()

打印出来:

ValueError: x and y must have same first dimension 

我从这个网站搜索。我发现 x 不能是列表。我尝试了一些我搜索过的日期时间等但又出错了:(

我怎样才能以这种方式或其他方式做到这一点?还有比我更基本的方法吗?

我只想绘制一个图表,我希望它的 x 轴从 8:27(示例)开始,我必须以 8:47(示例)结束。但只能在图表上看到 8:30 ,8:35, 8,40 , 8:45 (5 分钟间隔)。这些时间可以更改。因为我必须从文件中读取这些。如果文件中的时间从 3:47(示例)开始,图表必须从 3:47 开始,并且必须以 4:03(示例)结束。但就像我说的,只有 3:50、3:55、4:00 必须在图 x 轴上。我的文件确实是一个巨大的字典文件。时间逐行保存在 d[time] 中。

【问题讨论】:

  • 你能试着澄清一下你在这里做什么吗?你的输入文件中有什么? pd1grapdict 是什么?您的错误通常表明您为 xy 数据提供了两个不同大小的数组。如果您可以提供Minimal, Complete, and Verifiable example,它将大大有助于回答您的问题。
  • 对不起,你是对的。我只想绘制一个图表,我希望它的 x 轴从 8:27(示例)开始,我必须以 8:47(示例)结束。但只能在图表上看到 8:30 ,8:35, 8,40 , 8:45 (5 分钟间隔)。这些时间可以更改。因为我必须从文件中读取这些。如果文件中的时间从 3:47(示例)开始,图表必须从 3:47 开始,并且必须以 4:03(示例)结束。但就像我说的,只有 3:50、3:55、4:00 必须在图 x 轴上。我的文件确实是一个巨大的字典文件。时间逐行保存在 d[time] 中。

标签: python json datetime graph plot


【解决方案1】:

撇开你的 x 和 y 值在不同的文件中,假设你使用 matplotlib 进行绘图,我认为最好的方法是使用 Python datetime 包来转换你的x 值到datetime 对象。然后 matplotlib 可以直接将这些对象用于 x 值。如果您的 x 值看起来像“2015-01-03 01:15:00”,您可以将它们转换为 datetime,如下所示:

import datetime
x = datetime.datetime.strptime( '2015-01-03 01:15:00', '%Y-%m-%d %H:%M:%S')

在绘制数据时,您需要确保 x 和 y 列表的长度相同,尤其是因为您是从单独的文件中提取它们。然后你就可以按照这个例子做你想做的事了:

import matplotlib.pyplot as plt
import datetime
from numpy import sin, arange
from math import pi

starttime = datetime.datetime(2015, 12, 8, 8, 37, 0)
delta = datetime.timedelta(minutes=1)

# Create label locations and strings
sample_times = [starttime + i * delta for i in range(60)]
label_locations = [d for d in sample_times if d.minute % 5 == 0]
labels = [d.strftime('%Y-%m-%d %H:%M:%S') for d in label_locations]

# Create some y data to plot
x = arange(60)
y = sin(x * 2 * pi / 60.0)

# Do the plotting. You'll probably want to make adjustments to accommodate the size 
# of the labels.
plt.plot(sample_times, y)
plt.xticks(label_locations, labels, rotation=90)
plt.show()

【讨论】:

  • 感谢您的帮助。抱歉,我很晚才写感谢信 :(