我试图复制一个绘图示例,但是遇到了x轴和日期范围的问题。当包含plt.hlines()时,范围可以追溯到1970年。删除时,日期范围是正确的。是什么引起了这个问题?
import yfinance as yf
import matplotlib.pyplot as plt
AAPL = yf.download('AAPL', start = '2020-4-5', end = '2021-6-5',)
data = AAPL['Close']
mean = AAPL['Close'].mean()
std = AAPL['Close'].std()
min_value = min(data)
max_value = max(data)
plt.title("AAPL")
plt.ylim(min_value -20, max_value + 20)
plt.scatter(x=AAPL.index, y=AAPL['Close'])
plt.hlines(y=mean, xmin=0, xmax=len(data)) # If this line is Removed, the X axis works with Date Range.
plt.show()


发布于 2022-07-06 04:04:23
问题是:
plt.hlines(y=mean, xmin=0, xmax=len(data)) # If this line is Removed, the X axis works with Date Range.您的数据点在start = '2020-4-5', end = '2021-6-5'之间有数据
但是,当您使用hlines (水平线)时,xmin和xmax函数是参数,而不是假设它们是什么。
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.hlines.html
xmin,xmax指的是每一行的开始和结束。如果提供标量,则所有行都具有相同的长度。当您设置xmax=len(data)**,时,您要求在x轴上显示** len(data) “单位”。
当您删除代码片段中的plt.hlines时,实际上是要求matplotlib自动确定x轴范围,这就是它工作的原因。
也许你要找的是指定日期范围。
plt.xlim([datetime.date(2020, 4, 5), datetime.date(2021, 6, 5)])完整的例子:
import datetime
import yfinance as yf
import matplotlib.pyplot as plt
AAPL = yf.download('AAPL', start = '2020-4-5', end = '2021-6-5',)
data = AAPL['Close']
mean = AAPL['Close'].mean()
std = AAPL['Close'].std()
min_value = min(data)
max_value = max(data)
plt.title("AAPL")
plt.ylim(min_value -20, max_value + 20)
plt.xlim([datetime.date(2020, 4, 5), datetime.date(2021, 6, 5)])
plt.scatter(x=AAPL.index, y=AAPL['Close'])
plt.show()

https://stackoverflow.com/questions/72877785
复制相似问题