gpt4 book ai didi

python - 从 Numpy 数组问题中绘制日期

转载 作者:行者123 更新时间:2023-11-28 17:46:29 25 4
gpt4 key购买 nike

我正在绘制天气数据的 CSV 文件,我在代码中导入它时效果很好,但我正在尝试绘制它。以下是 CSV 数据的示例:

12:00am,171,6,7,52,76,77.1,63.7,28.74,0.00,0.00,0.0,0,63.7,78.1,67.4,56.0,29.96
12:01am,192,4,6,52,76,77.1,63.7,28.74,0.00,0.00,0.0,0,63.7,78.1,67.4,56.0,29.96
12:02am,197,3,6,52,76,77.1,63.7,28.74,0.00,0.00,0.0,0,63.7,78.1,67.4,56.0,29.96
12:03am,175,3,6,52,76,77.1,63.7,28.73,0.00,0.00,0.0,0,63.7,78.1,67.4,56.0,29.96
12:04am,194,4,6,52,76,77.1,63.7,28.73,0.00,0.00,0.0,0,63.7,78.1,67.4,56.0,29.96
12:05am,148,5,6,52,76,77.1,63.7,28.73,0.00,0.00,0.0,0,63.7,78.1,67.4,56.0,29.96

无论如何,我希望时间在 X 轴上,但我无法使用 matplotlib 绘制它。我尝试了一种使用 xticks 的方法,它绘制了我的 y 值,仅此而已。它只是在我的 X 轴上给了我一条粗实线。

import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from matplotlib.dates import date2num
import datetime as DT
import re

data = np.genfromtxt('FILE.csv', delimiter=',', dtype=None, skip_header=3)
length = len(data)

x = data['f0']
y = data['f7']

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_title("Temperature")
ax1.set_xlabel('Time')
ax1.set_ylabel('Degrees')


#plt.plot_date(x, y)
plt.show()
leg = ax1.legend()

plt.show()

我遗漏了一些关键部分,因为老实说,我不知道从这里到哪里去。我检查了我的 numpy 数组的数据类型,它一直说 numpy.ndarray,我找不到将其转换为字符串或 int 值以进行绘制的方法。这是一个 24 小时的 CSV 文件,我希望每 30 分钟左右有一个刻度线。有什么想法吗?

最佳答案

嗯,这不是很优雅,但它确实有效。关键是将存储在 x 中的时间(只是字符串)更改为日期时间对象,以便 matploblib 可以绘制它们。我创建了一个函数来执行转换并将其命名为 get_datetime_from_string

** 编辑代码以与 Python 2.7 兼容并处理个位数小时的时间 **

import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from matplotlib.dates import date2num
import datetime as DT
import re

def get_datetime_from_string(time_string):
''' Returns a datetime.datetime object

Args
time_string: a string of the form 'xx:xxam'
'''

# there's got to be a better way to do this.
# Convert it to utf-8 so string slicing works as expected.
time_string = unicode(time_string, 'utf-8')

# period is either am or pm
colon_position = time_string.find(':')
period = time_string[-2:]
hour = int(time_string[:colon_position])
if period.lower() == 'pm':
hour += 12

minute = int(time_string[colon_position + 1:colon_position + 3])

return DT.datetime(1,1,1,hour, minute)

data = np.genfromtxt('test.csv', delimiter=',', dtype=None, skip_header=3)
length=len(data)

x=data['f0']
y=data['f7']

datetimes = [get_datetime_from_string(t) for t in x]

fig = plt.figure()

ax1 = fig.add_subplot(111)

ax1.set_title("Temperature")
ax1.set_xlabel('Time')
ax1.set_ylabel('Degrees')

plt.plot(datetimes, y)
leg = ax1.legend()

plt.show()

我一直被绊倒,因为我试图在将 time_string 转换为 utf-8 之前对其进行字符串切片。在它给我 ASCII 值或其他东西之前。我不确定为什么转换它有帮助,但确实有帮助。

关于python - 从 Numpy 数组问题中绘制日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17477583/

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