如何在python中绘制3d图形

时间:2019-07-22 11:54:08

标签: python matplotlib graph 3d

我正在尝试在python中绘制3d图形。但我遇到一个错误:无法将字符串转换为浮点数2019-04-18 仅在一个特定的日期(即2019-04-18)显示此错误。 帮帮我。 PS-我是编码新手

from typing import List
import datetime as dt
from datetime import date
import pandas_datareader.data as web
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
X = input("Enter ticker name")

start = dt.datetime(2017, 1, 1)
end = date.today()
df = web.DataReader(X, 'yahoo', start, end)

dates: List[str] = []
for x in range(len(df)):
    new_date = str(df.index[x])
    new_date = new_date[0:10]
    dates.append(new_date)

close = df['Close']
high = df['High']
low = df['Low']
volume = df['Volume']

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(dates, volume, close, c='r', marker='o')
ax.set_xlabel('Date')
ax.set_ylabel('high')
ax.set_zlabel('Close')
plt.show()


error =  File "C:\Users\shrey\PycharmProject\Buysellhold\lib\site-packages\numpy\core\numeric.py", line 538, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: could not convert string to float: '2019-04-18'

1 个答案:

答案 0 :(得分:0)

将散点图与3D轴一起使用时,需要提供笛卡尔的x,y坐标。因此,您需要将用于x坐标的字符串转换为数值。一种方法是使用日期列表中每个日期与某个参考日期(例如列表中最早的日期)之间的天数,然后再重置xtick标签,例如

min_date = min(df.index)
days = [(dd-min_date).days for dd in df.index]
ax.scatter(days, volume, close, c='r', marker='o')
labels = ((min_date + pd.Timedelta(dd, unit='D')).date() for dd in ax.get_xticks())
ax.set_xticklabels(labels)
相关问题