如何在蜡烛图上方绘制多条线?

YON*_*JNS 4 python matplotlib

我有一个从 pylab_examples 示例代码创建 OHLC 图表的代码:来自http://matplotlib.org/examples/pylab_examples/finance_demo.html的 Finance_demo.py :

图表输出

在此输入图像描述

然后我尝试在迄今为止的 20 处绘制一条水平线,但出现空图错误。

这是代码:

#!/usr/bin/env python
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, WeekdayLocator,\
    DayLocator, MONDAY
from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc


# (Year, month, day) tuples suffice as args for quotes_historical_yahoo
date1 = (2004, 2, 1)
date2 = (2004, 4, 12)


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

quotes = quotes_historical_yahoo_ohlc('INTC', date1, date2)
if len(quotes) == 0:
    raise SystemExit

fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(weekFormatter)
#ax.xaxis.set_minor_formatter(dayFormatter)

#plot_day_summary(ax, quotes, ticksize=3)
candlestick_ohlc(ax, quotes, width=0.6)

ax.xaxis_date()
ax.autoscale_view()
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')

plt.show()
Run Code Online (Sandbox Code Playgroud)

如何添加更多行?

谢谢。

小智 5

您不能再次使用该轴来绘制已用于绘制烛台图的其他内容。

您需要另一个轴,即添加同一区域的另一个子图。

from matplotlib.finance import candlestick_ochl
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mticker

fig = plt.figure()
ax1 = fig.add_subplot(111) # in this function, first number 1 represent the height,
# second is for width and third is the plot number
ax2 = fig.add_subplot(111) # make sure both have same arguments for add_subplot function

ochl = [[mdates.date2num(datetime.date(2014, 12, 29)),20,30,35,15],
    [mdates.date2num(datetime.date(2015, 1, 30)),21,14,40,10],
    [mdates.date2num(datetime.date(2015, 2, 28)),23,29,45,15]]

# it is in the same expected order    date,open,high,low,close
candlestick_ochl(ax1, ochl, width=4, colorup='g', colordown='r', alpha=1)
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax1.xaxis.set_major_locator(mticker.MaxNLocator(4))
ax1.grid(True)
ax2.plot([mdates.date2num(datetime.date(2014, 12, 29)),mdates.date2num(datetime.date(2015, 1, 29))],[20,30],color = 'b')
# make sure in the second plot, the xaxis is also like date type converted to number by date2num function
plt.show()
Run Code Online (Sandbox Code Playgroud)

以及上面代码的结果

绘制上述代码的图

在此输入图像描述