如何在烛台图表上绘制多条线?

时间:2016-06-15 10:24:46

标签: python matplotlib

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

图表输出

enter image description here

然后我尝试在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()

如何添加更多行?

谢谢。

1 个答案:

答案 0 :(得分:4)

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

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

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

以及上述代码的结果

绘制上述代码

enter image description here