在 matplotlib 中的日期时间轴上绘制矩形?

Plot rectangles over datetime axis in matplotlib?

我正在尝试使用 matplotlib 手动创建烛台图表,使用 errorbar 作为每日最高价和最低价,使用 Rectangle() 作为调整后的收盘价和开盘价。 似乎具备完成此任务的所有先决条件。

我试图非常忠实地使用上面的内容,但是在 datetime64[ns] 的 x 轴上绘制一些东西的问题给了我无穷无尽的错误,所以我另外尝试合并 关于日期时间的绘图。

到目前为止,这是我的代码,对于其中的混乱,我们深表歉意:

import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle

def makeCandles(xdata,high,low,adj_close,adj_open,fc='r',ec='None',alpha=0.5):

    ## Converting datetimes to numerical format matplotlib can understand.
    dates = mdates.date2num(xdata)

    ## Creating default objects
    fig,ax = plt.subplots(1)

    ## Creating errorbar peaks based on high and low prices
    avg = (high + low) / 2
    err = [high - avg,low - avg]

    ax.errorbar(dates,err,fmt='None',ecolor='k')

    ## Create list for all the error patches
    errorboxes = []

    ## Loop over data points; create "body" of candlestick 
    ## based on adjusted open and close prices

    errors=np.vstack((adj_close,adj_open))
    errors=errors.T

    for xc,yc,ye in zip(dates,avg,errors):
        rect = Rectangle((xc,yc-ye[0]),1,ye.sum())
        errorboxes.append(rect)

    ## Create patch collection with specified colour/alpha
    pc = PatchCollection(errorboxes,facecolor=fc,alpha=alpha,edgecolor=ec)

    ## Add collection to axes
    ax.add_collection(pc)

    plt.show()

我的数据看起来像

这就是我尝试 运行,首先从 quandl 得到价格 table,

import quandl as qd
api =  '1uRGReHyAEgwYbzkPyG3'
qd.ApiConfig.api_key = api 

data = qd.get_table('WIKI/PRICES', qopts = { 'columns': ['ticker', 'date', 'high','low','adj_open','adj_close'] }, \
                        ticker = ['AMZN', 'XOM'], date = { 'gte': '2014-01-01', 'lte': '2016-12-31' })
data.reset_index(inplace=True,drop=True)

makeCandles(data['date'],data['high'],data['low'],data['adj_open'],data['adj_close'])

代码运行没有错误,但输出一个空图。所以我要的是关于如何在日期时间日期上绘制这些矩形的建议。对于矩形的宽度,我简单地把一个统一的“1”作为bec。我不知道指定矩形日期时间宽度的简单方法。

编辑

这是我目前得到的图,已将我的 xdata 转换为 matplotlib mdates:

在我通过 mdates 转换 xdata 之前,到处都是 xdata 作为我的 x 轴,这是我不断遇到的错误之一:

要获得您想要的情节,需要考虑几件事。首先,您要检索股票 AMZNXOM,显示两者会使您想要的图表看起来很有趣,因为数据相距甚远。其次,您在其中绘制数年每一天的烛台图表将变得非常拥挤。最后,您需要将序号日期格式化回 x 轴。

如评论中所述,您可以使用可通过 mpl_finance 访问的预构建 matplotlib candlestick2_ohlc 函数(尽管已弃用),如 答案所示进行安装。我选择仅使用带有内置误差线的 matplotlib 条形图。

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import quandl as qd
from matplotlib.dates import DateFormatter, WeekdayLocator, \
    DayLocator, MONDAY

# get data
api = '1uRGReHyAEgwYbzkPyG3'
qd.ApiConfig.api_key = api
data = qd.get_table('WIKI/PRICES', qopts={'columns': ['ticker', 'date', 'high', 'low', 'open', 'close']},
                    ticker=['AMZN', 'XOM'], date={'gte': '2014-01-01', 'lte': '2014-03-10'})
data.reset_index(inplace=True, drop=True)

fig, ax = plt.subplots(figsize = (10, 5))
data['date'] = mdates.date2num(data['date'].dt.to_pydatetime()) #convert dates to ordinal
tickers = list(set(data['ticker'])) # unique list of stock names
for stock_ind in tickers:
    df = data[data['ticker'] == 'AMZN'] # select one, can do more in a for loop, but it will look funny

    inc = df.close > df.open
    dec = df.open > df.close

    ax.bar(df['date'][inc],
           df['open'][inc]-df['close'][inc],
           color='palegreen',
           bottom=df['close'][inc],
           # this yerr is confusing when independent error bars are drawn => (https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.errorbar)
           yerr = [df['open'][inc]-df['high'][inc], -df['open'][inc]+df['low'][inc]],
           error_kw=dict(ecolor='gray', lw=1))

    ax.bar(df['date'][dec],
           df['close'][dec]-df['open'][dec],
           color='salmon', bottom=df['open'][dec],
           yerr = [df['close'][dec]-df['high'][dec], -df['close'][dec]+df['low'][dec]],
           error_kw=dict(ecolor='gray', lw=1))

    ax.set_title(stock_ind)

#some tweaking, setting the dates
mondays = WeekdayLocator(MONDAY)  # major ticks on the mondays
alldays = DayLocator()  # minor ticks on the days
weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
dayFormatter = DateFormatter('%d')  # e.g., 12
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(weekFormatter)
ax.set_ylabel('monies ($)')

plt.show()