gpt4 book ai didi

python - 需要 matplotlib 中日期时间系列 3D 绘图的帮助

转载 作者:行者123 更新时间:2023-12-03 08:47:58 25 4
gpt4 key购买 nike

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.gca(projection = '3d')

x = np.zeros((2, 24), dtype = 'datetime64[h]')
x[0, : ] = np.arange('2020-02-27', '2020-02-28', dtype = 'datetime64[h]')
x[1, : ] = np.arange('2020-02-28', '2020-02-29', dtype = 'datetime64[h]')

y = np.zeros((2, 24), dtype = 'datetime64[D]')
y[0, : ] = np.array(['2020-02-27' for i in range(24)])
y[1, : ] = np.array(['2020-02-28' for i in range(24)])

z = np.zeros((2, 24))
z[0, : ] = np.arange(24)
z[1, : ] = np.arange(24)

surf = ax.plot_surface(x, y, z)

plt.show()

我想绘制 3D 效果,如下所示:

enter image description here

但出现以下错误消息:“类型错误:float() 参数必须是字符串或数字,而不是‘datetime.timedelta’”

我该怎么做?

最佳答案

虽然有一个plot_date函数对 datetime.timedelta 进行操作,在您的情况下,您无法在 3D 中使用该函数。相反,您可以创建一个 int/float 数组来表示该数据,方法是使用 matplotlib.dates.date2num() 将日期转换为数字。 。然后您可以将刻度标签设置为您想要的任何格式。我使用了下面的默认 timedelta

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.dates as dates

fig = plt.figure()
ax = fig.gca(projection = '3d')

x = np.zeros((2, 24), dtype = 'datetime64[h]')
x[0, : ] = np.arange('2020-02-27', '2020-02-28', dtype = 'datetime64[h]')
x[1, : ] = np.arange('2020-02-28', '2020-02-29', dtype = 'datetime64[h]')
# convert the datetime to num
xt = [[dates.date2num(d) for d in xi] for xi in x]

y = np.zeros((2, 24), dtype = 'datetime64[D]')
y[0, : ] = np.array(['2020-02-27' for i in range(24)])
y[1, : ] = np.array(['2020-02-28' for i in range(24)])
# convert the datetime to num
yt = [[dates.date2num(d) for d in yi] for yi in y]

z = np.zeros((2, 24))
z[0, : ] = np.arange(24)
z[1, : ] = np.arange(24)

surf = ax.plot_surface(xt, yt, z)
# set x labels as diff in hours
ax.set_xticklabels(x[0]-min(x[0]))
# set y labels as the two dates
ax.set_yticklabels([y[0][0],'','','','',y[1][0]])
plt.show()

结果如下。 enter image description here

关于python - 需要 matplotlib 中日期时间系列 3D 绘图的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60589494/

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