如何使用熊猫中的DataFrame在图形的x轴上显示日期

时间:2018-07-06 10:54:23

标签: python python-3.x pandas matplotlib data-visualization

我编写了以下代码:

import pandas as pd     
from pandas_datareader import data as wb            
import numpy as np      
import matplotlib.pyplot as plt         
import matplotlib.dates as dates
assets= ["WMT", "FB"]  
source=pd.read_csv("C:/Users/HarshitGoyal/Downloads/Walmart_FB_2014_2017.csv", index_col="Date")     
source= (source/source.iloc[0])*100      
source.plot(figsize=(10,5))      

并获得以下输出(请单击下面的URL):

此处,日期显示在图形上,但不显示值。请帮忙! 附注-我是Python的初学者。

pic

Here is the link of the CSV file of the data.

1 个答案:

答案 0 :(得分:0)

密钥是您的source.indexstr类型。由于您使用的是股票价格(即时间序列数据),因此更好的方法是将索引转换为datetime类型,并使用以下参数:parse_dates=True

>>> df = pd.read_csv('Walmart_FB_2014_2017.csv', index_col='Date', parse_dates=True)
>>> dff = df / df.iloc[0]
>>> dff.plot()

对于简单的情节图,内置的visualization熊猫功能也可以正常工作。

enter image description here

检查dtype的区别:

>>> source = pd.read_csv('Walmart_FB_2014_2017.csv', index_col='Date')
>>> source.index
Index(['2013-12-31', '2014-01-02', '2014-01-03', '2014-01-06', '2014-01-07',
       ...
       '2017-04-03', '2017-04-04', '2017-04-05', '2017-04-06', '2017-04-07'],
      dtype='object', name='Date', length=824)
>>> # Note the differences.
>>> df = pd.read_csv('Walmart_FB_2014_2017.csv', index_col='Date', parse_dates=True)
>>> df.index
DatetimeIndex(['2013-12-31', '2014-01-02', '2014-01-03', '2014-01-06',
               ...
               '2017-04-04', '2017-04-05', '2017-04-06', '2017-04-07'],
              dtype='datetime64[ns]', name='Date', length=824, freq=None)