首页 > 解决方案 > Matplotlib 不在 X 轴上绘制水平线

问题描述

我有一个烛台图,我正在尝试绘制与 x 轴平行的水平线。我希望这条线在图表上的某个时间开始并在另一个时间结束,这是我尝试过的:

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

使用此代码,该线不会出现在图表上。Python 没有返回任何错误。

相反,如果我尝试这个:

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

我会看到这条线出现。问题是我不知道时间10对应于什么时间,所以我需要找到一种方法让它与日期一起使用。谁可以帮我这个事?

我在 x 轴上绘制的日期是正常的日期数组,如下所示:

[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)]

整体功能:

...
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)

当我尝试时输出plt.hlines(y=9520, xmin=date2num(datetime.datetime(2020, 5, 14, 10, 35)), xmax=date2num(datetime.datetime(2020, 5, 14, 5, 35)), color='g')

尝试时输出plt.hlines(y=9520, xmin=10, xmax=20, color='g') (预期输出,但我应该使用日期而不是 10、20)

标签: pythonpython-3.xmatplotlib

解决方案


使用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')

推荐阅读