gpt4 book ai didi

Python Matplotlib x 轴不正确地标记 timedelta64 对象

转载 作者:太空宇宙 更新时间:2023-11-03 15:40:02 24 4
gpt4 key购买 nike

我正在尝试使用 Matplotlib 从 Python 中的 Pandas 数据帧生成绘图。这是数据框的摘要。

import pandas as pd
import datetime
import matplotlib.pyplot as plt

# Summarize data frame.
>>> df.shape
(40, 4)

>>> df.dtypes
ID object
relative_time timedelta64[ns]
value float64
relative_value float64
dtype: object

>>> df.head()
ID relative_time value relative_value
0 001 -1 days +18:08:04 4.5 -1.0
1 001 -1 days +18:18:03 4.5 -1.0
2 001 -1 days +18:28:03 4.5 -1.0
3 001 -1 days +18:38:04 4.5 -1.0
4 001 -1 days +18:48:03 4.5 -1.0

>>> df.tail()
ID relative_time value relative_value
35 001 -1 days +23:58:03 5.5 0.0
36 001 00:08:03 5.5 0.0
37 001 00:18:03 5.5 0.0
38 001 00:28:02 5.5 0.0
39 001 00:38:04 5.5 0.0

我试图在 x 轴上绘制 relative_time 并在 y 轴上绘制 relative_value 。但是,下面的代码会产生意外的结果,我无法判断 x 轴的单位。

# Plot the desired plot.
plt.plot(test['relative_time'], test['relative_value'], marker='.')

enter image description here

请注意,上图中的 x 轴不是以小时为单位(相对于时间 0)。这样的情节如下所示。

plt.plot(test['relative_time'] / np.timedelta64(1, 'h'), test['relative_value'], marker='.')

enter image description here

如何绘制 x 轴,使其以与 relative_time 列相同的格式显示时间?例如,如果 x 轴每小时都有刻度线,则它们将被标记为 -1 days +18:00:00-1 days +19:00: 00、...、00:00:0001:00:00

最佳答案

x 轴的单位是纳秒,如输出所示

>>> df.dtypes
ID object
relative_time timedelta64[ns] <----- [ns] == nanoseconds
value float64
relative_value float64
dtype: object

看起来 matplotlib 仅显示纳秒,因此您需要将这些纳秒格式化为字符串格式。不幸的是,numpy.timedelta64 数据类型的功能是有限的,我在 numpy 文档中找不到任何可以做到这一点的内容。

示例 Formatted x-axis labels

来源: matplotlib intelligent axis labels for timedelta

import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib

fig = plt.figure()
ax = fig.add_subplot(111)

创建一个 np.timedelta64[ns] 值数组。这就是如果您执行 df["relative_time"].values 将会得到的结果。

# create list of times
x = [np.timedelta64(k, "ns") for k in range(0,300*10**9,10**9)]

# create some random y-axis data
y = np.random.random(len(x))

ax.plot(x, y)

# Function that formats the axis labels
def timeTicks(x, pos):
seconds = x / 10**9 # convert nanoseconds to seconds
# create datetime object because its string representation is alright
d = datetime.timedelta(seconds=seconds)
return str(d)

formatter = matplotlib.ticker.FuncFormatter(timeTicks)
ax.xaxis.set_major_formatter(formatter)
plt.show()

关于Python Matplotlib x 轴不正确地标记 timedelta64 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42216865/

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