如何使图表的水平轴显示日期

时间:2019-06-05 05:35:24

标签: python pandas

我一直试图在折线图上绘制数据,我希望它在水平轴上显示日期,我使用index_col将索引设置为日期,但是返回一个空的数据框。请

data = pd.read_csv('good_btc_dataset.csv', warn_bad_lines= True, 
index_col= ['date'])

data.dropna(inplace=True)
data.index = range(3169)
data.head()

我希望图表在水平轴上显示日期,但显示的只是数字 预先感谢

1 个答案:

答案 0 :(得分:0)

我建议您检查此脚本(it is a copy and paste from the documentation)。我认为您只需要调整自己的数据即可。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook

years = mdates.YearLocator()   # every year
months = mdates.MonthLocator()  # every month
years_fmt = mdates.DateFormatter('%Y')

# Load a numpy structured array from yahoo csv data with fields date, open,
# close, volume, adj_close from the mpl-data/example directory.  This array
# stores the date as an np.datetime64 with a day unit ('D') in the 'date'
# column.
with cbook.get_sample_data('goog.npz') as datafile:
    data = np.load(datafile)['price_data']

fig, ax = plt.subplots()
ax.plot('date', 'adj_close', data=data)

# format the ticks
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)
ax.xaxis.set_minor_locator(months)

# round to nearest years.
datemin = np.datetime64(data['date'][0], 'Y')
datemax = np.datetime64(data['date'][-1], 'Y') + np.timedelta64(1, 'Y')
ax.set_xlim(datemin, datemax)

# format the coords message box
ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.format_ydata = lambda x: '$%1.2f' % x  # format the price.
ax.grid(True)

# rotates and right aligns the x labels, and moves the bottom of the
# axes up to make room for them
fig.autofmt_xdate()

plt.show()