过去几天我一直在尝试无数次,但似乎找不到解决方法。
这是我的当前代码,其中包含一些注释:
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mdates
import datetime
import pandas_datareader.data as web
import matplotlib.ticker as ticker
from mpl_finance import candlestick2_ohlc
from matplotlib.dates import (MONDAY,DateFormatter,MonthLocator,WeekdayLocator,date2num)
# Define start and end date
end = datetime.datetime.now()
start = end - datetime.timedelta(days=63)
# Load data for the specific stock
quotes = web.DataReader('AAPL','yahoo',start,end)
quotes['Date'] = quotes.index
# Order the dataframe
quotes = quotes[['Date','Open','High','Low','Close']]
# 2019-09-16 217.729996 220.130005 217.559998 219.899994
fig,ax = plt.subplots()
candlestick2_ohlc( ax,quotes['Open'],quotes['High'],quotes['Low'],quotes['Close'],width=0.5,colorup='g',colordown='r')
#ax.xaxis.set_major_locator(ticker.MaxNLocator(8))#I was just testing with this
def mydate(x,pos):
try:
a = quotes['Date'][int(x)]
# print(a) --> 2019-11-04 00:00:00
# type(a) --> <class 'pandas._libs.tslibs.timestamps.Timestamp'>
a = pd.to_datetime(a) # doesn't work
return a
except IndexError:
return ''
ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
fig.autofmt_xdate()
fig.tight_layout()
plt.show()
这是输出:
如您所见,它显示的日期如下: 2019-11-04 00:00:00
我的目标是显示这样的日期:
我已尽力清理代码,以使其更易于阅读和理解。