2

I have a candlestick chart, i'm trying to plot horizontal lines parallel to the x axis. I would like the line to start at a certain time on the chart and finish at another time, here is what i tried:

plt.hlines(y=9520, xmin=datetime.datetime(2020, 5, 14, 5, 35), xmax=datetime.datetime(2020, 5, 14, 13, 0), color='g')

With this code, the line won't appear on the chart. Python did not return any error.

Instead, if i try this:

plt.hlines(y=9520, xmin=10, xmax=20), color='g')

I will see the line appearing. The problem is that i don't know to what time does 10 correspond to, so i need to find a way to make it work with dates, instead. Can anyone help me on this?

The dates i'm plotting on the x axis is a normal array of dates, looks like this:

[datetime.datetime(2020, 5, 14, 5, 30), datetime.datetime(2020, 5, 14, 5, 35), datetime.datetime(2020, 5, 14, 5, 40), datetime.datetime(2020, 5, 14, 5, 45), datetime.datetime(2020, 5, 14, 5, 50), datetime.datetime(2020, 5, 14, 5, 55), datetime.datetime(2020, 5, 14, 6, 0), datetime.datetime(2020, 5, 14, 6, 5), datetime.datetime(2020, 5, 14, 6, 10), datetime.datetime(2020, 5, 14, 6, 15), datetime.datetime(2020, 5, 14, 6, 20), datetime.datetime(2020, 5, 14, 6, 25), datetime.datetime(2020, 5, 14, 6, 30), datetime.datetime(2020, 5, 14, 6, 35), datetime.datetime(2020, 5, 14, 6, 40), datetime.datetime(2020, 5, 14, 6, 45), datetime.datetime(2020, 5, 14, 6, 50), datetime.datetime(2020, 5, 14, 6, 55), datetime.datetime(2020, 5, 14, 7, 0), datetime.datetime(2020, 5, 14, 7, 5), datetime.datetime(2020, 5, 14, 7, 10), datetime.datetime(2020, 5, 14, 7, 15), datetime.datetime(2020, 5, 14, 7, 20), datetime.datetime(2020, 5, 14, 7, 25), datetime.datetime(2020, 5, 14, 7, 30), datetime.datetime(2020, 5, 14, 7, 35), datetime.datetime(2020, 5, 14, 7, 40), datetime.datetime(2020, 5, 14, 7, 45), datetime.datetime(2020, 5, 14, 7, 50), datetime.datetime(2020, 5, 14, 7, 55)]

The whole function:

...
dates = [x[0] for x in ohlc]
dates = np.asarray(dates)

opens = [x[1] for x in ohlc]
opens = np.asarray(opens)

highs = [x[2] for x in ohlc]
highs = np.asarray(highs)

lows = [x[3] for x in ohlc]
lows = np.asarray(lows)

closes = [x[4] for x in ohlc]
closes = np.asarray(closes)

volume = [x[5] for x in ohlc]
volume = np.asarray(volume)

unixs = [x[6] for x in ohlc]
unixs = np.asarray(unixs)

plt.close('all')


fig = plt.figure(facecolor='#131722',dpi=135)
#ax = fig.add_subplot(1,1,1)
ax1 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4, facecolor='#131722')


candlestick2_ohlc(ax1, opens, highs, lows, closes, width=FINALWIDTH, alpha=1,colorup='#53B987', colordown='#EB4D5C')
ax1.xaxis.set_major_locator(mticker.MaxNLocator(8))


xdate = [datetime.fromtimestamp(i) for i in dates]


for label in ax1.xaxis.get_ticklabels():
    label.set_rotation(20)

def mydate(x,pos=None):
    try:
        if CandleFrame == '1D' or CandleFrame == '4H':
            return xdate[int(x)].strftime('%m/%d %H:%M')
        else:
            t = xdate[int(x)].strftime('%m-%d %H:%M')
            print(xdate)
            return xdate[int(x)].strftime('%m-%d %H:%M')

    except IndexError:
        return ''


try:
    plt.hlines(y=9520, xmin=datetime.datetime(2020, 5, 14, 10, 45), xmax=datetime.datetime(2020, 5, 14, 12, 25), color='g')

except Exception as e:
    print(e)

ax1.xaxis.set_major_formatter(mticker.FuncFormatter(mydate))
ax1.grid(False, color='#242938', alpha=0.5, ls='dotted')
ax1.spines['bottom'].set_color("#131722")
ax1.spines['top'].set_color("#131722")
ax1.spines['left'].set_color("#131722")
ax1.spines['right'].set_color("#131722")
ax1.tick_params(axis='both', colors='w')
ax1.set_axisbelow(True)
plt.gca().yaxis.set_major_locator(mticker.MaxNLocator())


if CandleFrame == '1D' or CandleFrame == '4H':
    xdates = [i.strftime('%m/%d %H:%M') for i in xdate]
else:
    xdates = [i.strftime('%m/%d %H:%M') for i in xdate]


plt.title('%s-%s (%s) %s - Bitcoin Levels' % (MainMarket,CoinName,Exchange,CandleFrame), color='w')
plt.subplots_adjust(left=0.18, bottom=0.09, right=0.98, top=1, wspace=0.2, hspace=0)

Output when i try plt.hlines(y=9520, xmin=date2num(datetime.datetime(2020, 5, 14, 10, 35)), xmax=date2num(datetime.datetime(2020, 5, 14, 5, 35)), color='g'):

Output when i try plt.hlines(y=9520, xmin=10, xmax=20, color='g') (EXPECTED OUTPUT, but i should use dates instead of 10, 20)

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Jack022
  • 867
  • 6
  • 30
  • 91
  • can publish tha full spinnet of code? ... Does python return any error? – Stoic Lion May 14 '20 at 15:19
  • @FireLion90 yes, i just did! – Jack022 May 14 '20 at 15:26
  • are you sure that you write in the statement the real data range? you write hard-coded the data for x-axis. They can be out of dates's range. Can you add an image of the generated plot? – Stoic Lion May 14 '20 at 15:30
  • @FireLion90 yes, i added 2 screenshots, should be a lot more helpful now – Jack022 May 14 '20 at 15:36
  • can this [old-post](https://stackoverflow.com/questions/1574088/plotting-time-in-python-with-matplotlib) useful for you? – Stoic Lion May 14 '20 at 15:52
  • I've already been suggested to use date2num but it didn't work unfortunately (see answer below) – Jack022 May 14 '20 at 16:35
  • [Acessing mplfinance Figure and Axes objects](https://github.com/matplotlib/mplfinance/wiki/Acessing-mplfinance-Figure-and-Axes-objects) – Trenton McKinney Jul 16 '23 at 21:13
  • Given `fig, axes = mpf.plot(...)`, `axes[0].get_xticks()` shows the xticks are 0 indexed. This is not a continues datetime axes, and this tick values do not correspond to dates. – Trenton McKinney Jul 16 '23 at 21:30

1 Answers1

2

Use date2num:

from matplotlib.dates import date2num

plt.hlines(y=9520, xmin=date2num(datetime.datetime(2020, 5, 14, 5, 35)), 
                   xmax=date2num(datetime.datetime(2020, 5, 14, 13, 0)), color='g')
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
  • Thank you for your answer! I tried with date2num but i still don't see the line. I'm looking for errors but there doesn't seem to be one – Jack022 May 14 '20 at 15:27