首页 > 解决方案 > 如何在 Matplotlib 上的两个数据点之间绘制一条水平线?

问题描述

我在 Matplotlib 上创建了一个烛台图,现在我想在上面画更多东西。

这是我的代码::

...
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(t)
            return xdate[int(x)].strftime('%m/%d %H:%M')

    except IndexError:
        return ''
        #return pl.num2date(x).strftime('%Y-%m-%d')



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


try:
    plt.hlines(y=9125, xmin='05/13 05:30', xmax='05/13 10:30', color='g')

except Exception as e:
    print(e)


plt.cla()
plt.close()
...
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(t)
            return xdate[int(x)].strftime('%m/%d %H:%M')

    except IndexError:
        return ''
        #return pl.num2date(x).strftime('%Y-%m-%d')



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

plt.cla()
plt.close()

x 轴上的数据如下所示:

[datetime.datetime(2020, 5, 14, 22, 40), datetime.datetime(2020, 5, 14, 22, 45), datetime.datetime(2020, 5, 14, 22, 50), datetime.datetime(2020, 5, 14, 22, 55), datetime.datetime(2020, 5, 14, 23, 0), datetime.datetime(2020, 5, 14, 23, 5), datetime.datetime(2020, 5, 14, 23, 10), datetime.datetime(2020, 5, 14, 23, 15), datetime.datetime(2020, 5, 14, 23, 20), datetime.datetime(2020, 5, 14, 23, 25), datetime.datetime(2020, 5, 14, 23, 30), datetime.datetime(2020, 5, 14, 23, 35), datetime.datetime(2020, 5, 14, 23, 40), datetime.datetime(2020, 5, 14, 23, 45), datetime.datetime(2020, 5, 14, 23, 50), datetime.datetime(2020, 5, 14, 23, 55), datetime.datetime(2020, 5, 15, 0, 0), datetime.datetime(2020, 5, 15, 0, 5), datetime.datetime(2020, 5, 15, 0, 10), datetime.datetime(2020, 5, 15, 0, 15), datetime.datetime(2020, 5, 15, 0, 20), datetime.datetime(2020, 5, 15, 0, 25), datetime.datetime(2020, 5, 15, 0, 30), datetime.datetime(2020, 5, 15, 0, 35), datetime.datetime(2020, 5, 15, 0, 40), datetime.datetime(2020, 5, 15, 0, 45), datetime.datetime(2020, 5, 15, 0, 50), datetime.datetime(2020, 5, 15, 0, 55), datetime.datetime(2020, 5, 15, 1, 0), datetime.datetime(2020, 5, 15, 1, 5), datetime.datetime(2020, 5, 15, 1, 10), datetime.datetime(2020, 5, 15, 1, 15), datetime.datetime(2020, 5, 15, 1, 20), datetime.datetime(2020, 5, 15, 1, 25), datetime.datetime(2020, 5, 15, 1, 30), datetime.datetime(2020, 5, 15, 1, 35), datetime.datetime(2020, 5, 15, 1, 40), datetime.datetime(2020, 5, 15, 1, 45), datetime.datetime(2020, 5, 15, 1, 50), datetime.datetime(2020, 5, 15, 1, 55), datetime.datetime(2020, 5, 15, 2, 0), datetime.datetime(2020, 5, 15, 2, 5), datetime.datetime(2020, 5, 15, 2, 10), datetime.datetime(2020, 5, 15, 2, 15), datetime.datetime(2020, 5, 15, 2, 20), datetime.datetime(2020, 5, 15, 2, 25), datetime.datetime(2020, 5, 15, 2, 30), datetime.datetime(2020, 5, 15, 2, 35), datetime.datetime(2020, 5, 15, 2, 40), datetime.datetime(2020, 5, 15, 2, 45), datetime.datetime(2020, 5, 15, 2, 50), datetime.datetime(2020, 5, 15, 2, 55), datetime.datetime(2020, 5, 15, 3, 0), datetime.datetime(2020, 5, 15, 3, 5), datetime.datetime(2020, 5, 15, 3, 10), datetime.datetime(2020, 5, 15, 3, 15), datetime.datetime(2020, 5, 15, 3, 20), datetime.datetime(2020, 5, 15, 3, 25), datetime.datetime(2020, 5, 15, 3, 30), datetime.datetime(2020, 5, 15, 3, 35), datetime.datetime(2020, 5, 15, 3, 40), datetime.datetime(2020, 5, 15, 3, 45), datetime.datetime(2020, 5, 15, 3, 50), datetime.datetime(2020, 5, 15, 3, 55), datetime.datetime(2020, 5, 15, 4, 0), datetime.datetime(2020, 5, 15, 4, 5), datetime.datetime(2020, 5, 15, 4, 10), datetime.datetime(2020, 5, 15, 4, 15), datetime.datetime(2020, 5, 15, 4, 20), datetime.datetime(2020, 5, 15, 4, 25), datetime.datetime(2020, 5, 15, 4, 30), datetime.datetime(2020, 5, 15, 4, 35), datetime.datetime(2020, 5, 15, 4, 40), datetime.datetime(2020, 5, 15, 4, 45), datetime.datetime(2020, 5, 15, 4, 50), datetime.datetime(2020, 5, 15, 4, 55), datetime.datetime(2020, 5, 15, 5, 0), datetime.datetime(2020, 5, 15, 5, 5), datetime.datetime(2020, 5, 15, 5, 10), datetime.datetime(2020, 5, 15, 5, 15), datetime.datetime(2020, 5, 15, 5, 20), datetime.datetime(2020, 5, 15, 5, 25), datetime.datetime(2020, 5, 15, 5, 30), datetime.datetime(2020, 5, 15, 5, 35), datetime.datetime(2020, 5, 15, 5, 40), datetime.datetime(2020, 5, 15, 5, 45), datetime.datetime(2020, 5, 15, 5, 50), datetime.datetime(2020, 5, 15, 5, 55), datetime.datetime(2020, 5, 15, 6, 0), datetime.datetime(2020, 5, 15, 6, 5), datetime.datetime(2020, 5, 15, 6, 10), datetime.datetime(2020, 5, 15, 6, 15), datetime.datetime(2020, 5, 15, 6, 20), datetime.datetime(2020, 5, 15, 6, 25), datetime.datetime(2020, 5, 15, 6, 30), datetime.datetime(2020, 5, 15, 6, 35), datetime.datetime(2020, 5, 15, 6, 40), datetime.datetime(2020, 5, 15, 6, 45), datetime.datetime(2020, 5, 15, 6, 50), datetime.datetime(2020, 5, 15, 6, 55), datetime.datetime(2020, 5, 15, 7, 0), datetime.datetime(2020, 5, 15, 7, 5), datetime.datetime(2020, 5, 15, 7, 10), datetime.datetime(2020, 5, 15, 7, 15), datetime.datetime(2020, 5, 15, 7, 20), datetime.datetime(2020, 5, 15, 7, 25), datetime.datetime(2020, 5, 15, 7, 30), datetime.datetime(2020, 5, 15, 7, 35), datetime.datetime(2020, 5, 15, 7, 40), datetime.datetime(2020, 5, 15, 7, 45), datetime.datetime(2020, 5, 15, 7, 50), datetime.datetime(2020, 5, 15, 7, 55), datetime.datetime(2020, 5, 15, 8, 0), datetime.datetime(2020, 5, 15, 8, 5), datetime.datetime(2020, 5, 15, 8, 10), datetime.datetime(2020, 5, 15, 8, 15), datetime.datetime(2020, 5, 15, 8, 20), datetime.datetime(2020, 5, 15, 8, 25), datetime.datetime(2020, 5, 15, 8, 30), datetime.datetime(2020, 5, 15, 8, 35), datetime.datetime(2020, 5, 15, 8, 40), datetime.datetime(2020, 5, 15, 8, 45), datetime.datetime(2020, 5, 15, 8, 50), datetime.datetime(2020, 5, 15, 8, 55), datetime.datetime(2020, 5, 15, 9, 0), datetime.datetime(2020, 5, 15, 9, 5), datetime.datetime(2020, 5, 15, 9, 10), datetime.datetime(2020, 5, 15, 9, 15), datetime.datetime(2020, 5, 15, 9, 20), datetime.datetime(2020, 5, 15, 9, 25), datetime.datetime(2020, 5, 15, 9, 30), datetime.datetime(2020, 5, 15, 9, 35), datetime.datetime(2020, 5, 15, 9, 40), datetime.datetime(2020, 5, 15, 9, 45), datetime.datetime(2020, 5, 15, 9, 50), datetime.datetime(2020, 5, 15, 9, 55), datetime.datetime(2020, 5, 15, 10, 0), datetime.datetime(2020, 5, 15, 10, 5), datetime.datetime(2020, 5, 15, 10, 10), datetime.datetime(2020, 5, 15, 10, 15)]

图表如下所示: 在此处输入图像描述

同时,我有一个如下所示的数据数组:

myData = [[9320, datetime.datetime(2020, 5, 15, 00, 20)'05/15 00:20'], [9440, datetime.datetime(2020, 5, 15, 8, 43)] ... ]

我想要做的是将这个数组绘制到烛台图表中。x=9320因此,例如,在图表上对应于时间的蜡烛下方应该有一条小线、一个圆圈或一个小矩形(无论如何正确可视化它)'05/15 00:20',所以它应该与那个蜡烛一样大x观点。

预期输出的示例:

我尝试了什么:

plt.hlines(y=9320, xmin=?, xmax=?, color='g')

此解决方案的问题:我可以轻松定位 y 轴,但我不明白如何在 x 轴上定位它。

有没有办法做到这一点?我能做些什么?例如,一个子图?

标签: pythonpython-3.xmatplotlib

解决方案


有几种方法。我发现最简单的方法是复制您关心的数据点的补丁(或矩形/条),然后将其y值设置为新的值。

由于您没有提供数据,因此我以 ebay 的一些旧股票价格为例。我无法获得matplotlib.finance您正在使用的确切版本,因为它已被弃用。稍后我可能会在虚拟环境中安装旧版本,但我确实让它在最新的mplfinance库中工作,尽管它的功能与您正在使用的功能几乎相同(我将包括如何更新到这个最后的模块):

从 Matplotlib API

matplotlib.finance.candlestick_ochl(...)返回(lines, patches)wherelines是添加的行patches列表,是添加的矩形补丁列表

所以,我从 的返回中获取那些补丁candlestick_ochl,复制你关心的那个,然后改变它的一些属性,比如颜色和位置。所有属性以及如何更改它们都在文档中

import copy 
...

lines, patches = candlestick_ohlc(ax1, ohlc[:5], width=0.4, colorup='#77d879', colordown='#db3f3f')

new_patch = copy.copy(patches[-3]) # must use copy, or you'll modify the original Rectangle. This grabs the 3rd one (right to left)
new_patch.set_y(148)
new_patch.set_color('white')
new_patch.set_height(0.3)

您还可以打印它以查看它的一些信息:

print(new_patch)

Rectangle(xy=(736534, 148), width=0.4, height=0.3, angle=0)

然后,当您进行绘图时,将其添加到绘图并重新调整您的视图:

# Add the patch to the Axes
ax1.add_patch(new_patch)
ax1.autoscale_view()

我放大了数据集以向您展示补丁。这是第三根烛台下的白色:

在此处输入图像描述

缩小(寻找小白条):

在此处输入图像描述
在此处输入图像描述

您还可以创建一个新矩形而不是复制旧矩形:

from matplotlib.patches import Rectangle
...

new_patch = Rectangle(xy=(736530, 155), width=0.4, height=0.3, angle=0, color='white')
ax1.add_patch(new_patch)
ax1.autoscale_view()

您甚至可以定义一个函数并将您关心的补丁传递给它,以使这变得非常容易:

def add_highlight(patch_to_highlight, y_position, color, height): 
    new_patch = copy.copy(patch_to_highlight)
    new_patch.set_y(y_position)
    new_patch.set_color(color)
    new_patch.set_height(height)
    ax1.add_patch(new_patch)
    ax1.autoscale_view()

这是我的完整代码。它适用于最新的mplfinanace

import copy
import urllib
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.patches import Rectangle
import matplotlib.ticker as mticker
from mplfinance.original_flavor import candlestick_ohlc


def bytespdate2num(fmt, encoding='utf-8'):
    strconverter = mdates.strpdate2num(fmt)
    def bytesconverter(b):
        s = b.decode(encoding)
        return strconverter(s)
    return bytesconverter

def add_highlight(ax, patch_to_highlight, y_position, color='white', height=0.3):
    new_patch = copy.copy(patch_to_highlight)
    new_patch.set_y(y_position)
    new_patch.set_color(color)
    new_patch.set_height(height)
    ax.add_patch(new_patch)
    ax.autoscale_view()

def graph_data(stock):
    # This is some old ebay stock price data
    stock_price_url = 'https://pythonprogramming.net/yahoo_finance_replacement'
    source_code = urllib.request.urlopen(stock_price_url).read().decode()
    stock_data = []
    split_source = source_code.split('\n')
    for line in split_source[1:]:
        split_line = line.split(',')
        if len(split_line) == 7:
            if 'values' not in line and 'labels' not in line:
                stock_data.append(line)

    # parse and organize the data
    date, closep, highp, lowp, openp, _, volume = np.loadtxt(stock_data, delimiter=',', unpack=True, converters={0: bytespdate2num('%Y-%m-%d')})
    x = 0
    y = len(date)
    ohlc = []
    while x < y:
        append_me = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x]
        ohlc.append(append_me)
        x+=1

    # do the plotting
    plt.style.use('dark_background')
    plt.figure()
    ax1 = plt.subplot2grid((1, 1), (0, 0))

    lines, patches = candlestick_ohlc(ax1, ohlc[:5], width=0.4, colorup='#53B987', colordown='#EB4D5C')

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

    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))

    ## Method with copying existing patch
    # new_patch = copy.copy(patches[-3])
    # new_patch.set_y(148)
    # new_patch.set_color('orange')
    # new_patch.set_height(0.3)
    # ax1.add_patch(new_patch)
    # ax1.autoscale_view()

    ## Method with making new Rectangle
    # new_patch = Rectangle(xy=(736530, 155), width=0.4, height=0.3, angle=0, color='orange')
    # ax1.add_patch(new_patch)
    # ax1.autoscale_view()

    ## Method using a function (cleanest)
    add_highlight(ax1, patches[-3], 136)

    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.title(stock)
    plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0)
    plt.tight_layout()
    plt.savefig('example.png')
    plt.show()

graph_data('EBAY')


更新到mplfinance

要获取当前的mplfinance,请使用 pip:pip install mplfinance

文档在这里

您应该在代码中更改的唯一一件事是您的导入:

from mplfinance.original_flavor import candlestick_ohlc

而这个函数调用(名称不同,需要返回值):

lines, patches = candlestick_ohlc((ax1, opens, highs, lows, closes, width=FINALWIDTH, alpha=1, colorup='#53B987', colordown='#EB4D5C')

推荐阅读