我有以下数据:
apple[0].head()
Out[76]:
Date Open High Low Close Adj Close Volume
0 1999-12-31 3.604911 3.674107 3.553571 3.671875 3.204494 40952800
1 2000-01-03 3.745536 4.017857 3.631696 3.997768 3.488905 133949200
2 2000-01-04 3.866071 3.950893 3.613839 3.660714 3.194754 128094400
3 2000-01-05 3.705357 3.948661 3.678571 3.714286 3.241507 194580400
4 2000-01-06 3.790179 3.821429 3.392857 3.392857 2.960991 191993200
我正在尝试在y轴上绘制价格(关闭),在x轴上绘制日期。
如果我写
plt.plot(apple[0]['Close'])
plt.title('AAPL Closing Prices')
plt.show()
它有效,但它在x轴上绘制数字,而我想在水平轴上显示日期。
我试过了
plt.plot(apple[0]['Date'],apple[0]['Close'])
plt.title('AAPL Closing Prices')
plt.show()
但它不起作用。我该如何运作?
如果有帮助,
apple[0]['Date']
的类型为pandas.core.series.Series
。apple[0].plot(x = 'Date', y = 'Close')
给我下面的图片
不显示2015年11月24日之后的日期。如何在x水平轴上显示更多日期?
最佳答案
您只能使用DataFrame方法,就像这样。
In[14]: apple[0]
Out[14]:
Date Open High Low Close Adj Close Volume
0 1999-12-31 3.604911 3.674107 3.553571 3.671875 3.204494 40952800
1 2000-01-03 3.745536 4.017857 3.631696 3.997768 3.488905 133949200
2 2000-01-04 3.866071 3.950893 3.613839 3.660714 3.194754 128094400
3 2000-01-05 3.705357 3.948661 3.678571 3.714286 3.241507 194580400
4 2000-01-06 3.790179 3.821429 3.392857 3.392857 2.960991 191993200
apple[0].plot(x = 'Date', y = 'Close')
该版本具有明确的matplotlib用法:
import matplotlib.pyplot as plt
from matplotlib import dates
from matplotlib.ticker import MultipleLocator
plt.plot(df['Date'], df['Close'])
plt.legend()
ax = plt.gca().get_xaxis()
ax.set_major_locator(MultipleLocator(1))
ax.set_minor_locator(MultipleLocator(0.1))
ax.set_major_formatter(dates.DateFormatter('%Y-%b-%d'))
for item in ax.get_ticklabels():
item.set_rotation(45)
关于python - Python绘图日期为X,价格为Y,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58506740/