wat*_*ter 2 python numpy matplotlib
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()
Run Code Online (Sandbox Code Playgroud)
我想绘制 3D 效果如下:
但出现以下错误消息:“TypeError: float() argument must be a string or a number, not '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()
Run Code Online (Sandbox Code Playgroud)