简体   繁体   中英

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?

在此处输入图像描述

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)

在此处输入图像描述

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM