为什么plt.hline()比数据中的日期数量显示长X轴的延长X轴? - matplotlib
我试图复制一个绘图示例,但遇到了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()
I'm trying to replicate a plot example but ran into an issue with the x axis and date range. When the plt.hlines() is included, the range goes back to 1970. When removed, the date range is correct. What could be causing the issue?
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是:
您的数据点具有
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)
时,您要求len(data)
“单位”要显示在X轴上。当您在代码段中删除该
plt.hlines
时,您实际上是要求matplotlib自动确定X轴范围,这就是为什么它可以使用。也许您要寻找的是指定日期范围,例如
完整示例:
The issue is with:
Your data points has data between
start = '2020-4-5', end = '2021-6-5'
But when you use the
hlines
(horizontal line), thexmin
andxmax
functions are the arguments not what you were assuming them to be.https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.hlines.html
xmin
,xmax
refers to the respective beginning and end of each line. If scalars are provided, all lines will have same length.When you set the
xmax=len(data)
, you are asking forlen(data)
"units" to be shown on the x-axis.When you remove that
plt.hlines
in your code snippet, you are essentially asking matplotlib to automatically determine the x-axis range, that is why it worked.Perhaps what you are looking for is to specify the date-range, e.g.
Full example: