python - 如何在 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'
解决方案
将 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)
推荐阅读
- php - MySql 和 PHP 的年份格式不同
- algorithm - 一个非常简单的算法的算法时间优化
- fractals - 以某种详细程度对 Mandelbrot 边缘点进行排序
- c++ - 通过指向数据成员的指针访问类成员是否被视为成员访问表达式?
- haskell - Xmonad 布局跟进
- typescript - Cucumber JS - 是否可以在 setDefinitionFunctionWrapper 中以编程方式设置 defaultTimeout 值?
- r - 在 R 中的函数中生成或处理缺少的参数
- c# - .Net Web App - 如何使用 UDP 端口 389 上的目录条目建立 LDAP 连接
- firebase - Firebase 分析无法在生产模式下运行 apk 颤振
- python - 在 Windows 上安装 Flac 命令行工具