【问题标题】:Matplotlib doesn't plot horizontal line on X axisMatplotlib 不在 X 轴上绘制水平线
【发布时间】:2020-05-14 15:13:01
【问题描述】:

我有一个烛台图,我正在尝试绘制与 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)

【问题讨论】:

  • 可以发布完整的代码吗? ... python 是否返回任何错误?
  • @FireLion90 是的,我刚刚做到了!
  • 你确定你在语句中写的是真实的数据范围吗?您为 x 轴编写硬编码数据。它们可能超出日期范围。您可以添加生成图的图像吗?
  • @FireLion90 是的,我添加了 2 个屏幕截图,现在应该会更有帮助
  • 这个old-post对你有用吗?

标签: python python-3.x matplotlib


【解决方案1】:

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

【讨论】:

  • 感谢您的回答!我尝试使用 date2num 但我仍然看不到这条线。我正在寻找错误,但似乎没有一个