首页 > 解决方案 > 如何在 python 中绘制 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'

标签: pythonmatplotlibgraph3d

解决方案


将 scatter 与 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)

推荐阅读