ValueError:序数必须为> = 1 [英] ValueError: ordinal must be >= 1
问题描述
此代码从Google财经获取一条直线的2个坐标,并将第3个点放在同一条线上一定距离。
This Code, Takes 2 co-ordinates for a straight line from google finance and places 3rd point on the same line at some distance.
import datetime as dt
from datetime import timedelta as td
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
import numpy as np
start = dt.datetime(2017, 7, 1)
end = dt.datetime(2017, 3, 1)
# retrieving data from google
df = web.DataReader('TSLA', 'google', start, )
Dates = df.index
Highs = df['High'] # Getting only the values from the 'High' Column.
Highest_high = np.amax(Highs) # returns the Highest value
for i, h in enumerate(Highs):
if h == Highest_high :
Highests_index = i
#Highests_index = Highs.argmax() # returns the index of Highest value
Highest_high_2 = sorted(Highs)[-2]
for i, j in enumerate(Highs):
if j == Highest_high_2 :
Highests_index_2 = i
#================Problem Maybe starting from here========================
x = [Highests_index, Highests_index_2]
y = [Highest_high, Highest_high_2]
coefficients = np.polyfit(x, y, 1)
polynomial = np.poly1d(coefficients)
# the np.linspace lets you set number of data points, line length.
x_axis = np.linspace(3,Highests_index_2 + 1, 3)
y_axis = polynomial(x_axis)
plt.plot(x_axis, y_axis)
plt.plot(x[0], y[0], 'go')
plt.plot(x[1], y[1], 'go')
plt.plot(Dates, Highs)
plt.grid('on')
plt.show()
大量Traceback发生以下错误
the following error occurs with lots of Traceback
dt = datetime.datetime.fromordinal(ix).replace(tzinfo = UTC)
ValueError:序数必须为> = 1
dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
ValueError: ordinal must be >= 1
上面的代码在我不使用datetime绘制数值的情况下也能很好地工作和大熊猫。我认为问题可能出在日期时间或matplotlib中。
The above code works well when I just plot the numeric values without using datetime and pandas. I think the issue might be in datetime or in matplotlib.
我知道这个问题看起来很重复,但是我无法将其问题与此处的任何其他解决方案联系起来。
I know this question might look duplicate, but I cannot relate my problem to any other solutions here.
推荐答案
该错误是由于matplotlib无法找到沿x轴的x轴值的位置造成的。
The error is due to matplotlib's inability to find the location of x-axis value along the x-axis.
前两行的绘图具有x轴的数值,而第三行则试图在同一行上绘制 datetime
轴。在绘制第三行 plt.plot(Dates,Highs)
时,matplotlib尝试查找该日期的x轴位置,并失败并显示错误。
The plot from the first two lines has numeric values for x-axis, whereas the third line is trying to plot a datetime
on the same axis. While plotting the third line plt.plot(Dates, Highs)
, matplotlib tries to find the x-axis location for the date and fails with the error.
这篇关于ValueError:序数必须为> = 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!