我在Ubuntu 10.0.4上使用matplotlib 1.2.x和Python 2.6.5。我正尝试创建一个由顶部阴谋和底部阴谋组成的单一阴谋。matplotlib:使用共享X轴创建两个(堆叠)子图但是分离Y轴值
X轴是时间序列的日期。顶部图包含数据的烛台图,底部图应由条形图组成 - 具有其自己的Y轴(也在左侧 - 与顶部图相同)。这两块地块不应重叠。
这是我迄今为止所做的一个片段。
datafile = r'/var/tmp/trz12.csv'
r = mlab.csv2rec(datafile, delimiter=',', names=('dt', 'op', 'hi', 'lo', 'cl', 'vol', 'oi'))
mask = (r["dt"] >= datetime.date(startdate)) & (r["dt"] <= datetime.date(enddate))
selected = r[mask]
plotdata = zip(date2num(selected['dt']), selected['op'], selected['cl'], selected['hi'], selected['lo'], selected['vol'], selected['oi'])
# Setup charting
mondays = WeekdayLocator(MONDAY) # major ticks on the mondays
alldays = DayLocator() # minor ticks on the days
weekFormatter = DateFormatter('%b %d') # Eg, Jan 12
dayFormatter = DateFormatter('%d') # Eg, 12
monthFormatter = DateFormatter('%b %y')
# every Nth month
months = MonthLocator(range(1,13), bymonthday=1, interval=1)
fig = pylab.figure()
fig.subplots_adjust(bottom=0.1)
ax = fig.add_subplot(111)
ax.xaxis.set_major_locator(months)#mondays
ax.xaxis.set_major_formatter(monthFormatter) #weekFormatter
ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.format_ydata = price
ax.grid(True)
candlestick(ax, plotdata, width=0.5, colorup='g', colordown='r', alpha=0.85)
ax.xaxis_date()
ax.autoscale_view()
pylab.setp(pylab.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
# Add volume data
# Note: the code below OVERWRITES the bottom part of the first plot
# it should be plotted UNDERNEATH the first plot - but somehow, that's not happening
fig.subplots_adjust(hspace=0.15)
ay = fig.add_subplot(212)
volumes = [ x[-2] for x in plotdata]
ay.bar(range(len(plotdata)), volumes, 0.05)
pylab.show()
我已成功使用上面的代码,以显示两个图,但是,有两个问题与底部曲线:
它完全覆盖第一(顶部)的底部部分情节 - 几乎就好像第二个情节与第一个情节一样绘制在同一个“画布”上 - 我看不到发生在哪里/为什么。
它用自己的指令覆盖现有的X轴,X轴值(日期)应该在两个图之间共享。
我在做什么错在我的代码?是否有人可以发现是什么导致第二个(底部)情节覆盖第一个(顶部)情节 - 我该如何解决这个问题?
这里是由上面的代码中创建的情节的屏幕截图:
[[编辑]]
修改代码由hwlau建议之后,这是新的情节。它比在这两个图是分开的第一更好,然而,以下问题仍然:
X轴应该由两个图可以共享(即,X轴应该显示仅用于第二[底部]图)
的第二图中的Y值似乎是正确formmated
我觉得这些问题s应该很容易解决,但是我的matplotlib fu目前并不好,因为我最近才开始用matplotlib编程。任何帮助都感激不尽。
子图中的'sharex'和'sharey'属性非常方便,感谢发布。 (它可以比通过读取和设置其他常见限制好得多:当通过交互式放大来检查结果时,如果共享,两个/所有子图将放大在一起。) – Bonlenfum 2013-05-13 16:05:47
'sharex = first_axis_instance'这是一个'轴'实例,对吗? – 2016-08-05 15:02:12