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?

enter image description here


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:

  1. set returnfig=True when calling mpf.plot()
  2. get the ticks from the returned x-axis
  3. format the ticks yourself (create tick labels)
  4. add one extra tick at the end.
  5. 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)

enter image description here

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:

enter image description here