【问题标题】:How to plot a 3d graph in python如何在 python 中绘制 3d 图形
【发布时间】:2019-11-30 09:35:45
【问题描述】:

我正在尝试在 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'

【问题讨论】:

    标签: python matplotlib graph 3d


    【解决方案1】:

    使用 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)
    

    【讨论】:

      猜你喜欢
      • 2015-10-03
      • 2011-01-18
      • 2023-04-03
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 1970-01-01
      • 2020-03-12
      相关资源
      最近更新 更多