Show last date on x axis for mplfinance chart
I've created a chart using mplfinance lib. I want to show the date for the last candle on x axis in the chart. How to achieve this?
Solution 1:
There is presently no direct way to do this with mplfinance (however there is an enhancement in progress that will help; see issue 428 and issue 313.
With a bit of work however, you can do this with the following workaround:
- set
returnfig=True
when callingmpf.plot()
- get the ticks from the returned x-axis
- format the ticks yourself (create tick labels)
- add one extra tick at the end.
- re-set the ticks and the tick labels.
Example code:
Given the following code and plot:
fig, axlist = mpf.plot(df, type='candle',style='yahoo',volume=True,returnfig=True)
We can do the following:
fig, axlist = mpf.plot(df, type='candle',style='yahoo',volume=True,returnfig=True)
newxticks = []
newlabels = []
##format = '%Y-%b-%d'
format = '%b-%d'
# copy and format the existing xticks:
for xt in axlist[0].get_xticks():
p = int(xt)
if p >= 0 and p < len(df):
ts = df.index[p]
newxticks.append(p)
newlabels.append(ts.strftime(format))
# Here we create the final tick and tick label:
newxticks.append(len(df)-1)
newlabels.append(df.index[len(df)-1].strftime(format))
# set the xticks and labels with the new ticks and labels:
axlist[0].set_xticks(newxticks)
axlist[0].set_xticklabels(newlabels)
# now display the plot:
mpf.show()
The result: