2012-04-04 247 views
13

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

我已成功使用上面的代码,以显示两个图,但是,有两个问题与底部曲线:

  1. 它完全覆盖第一(顶部)的底部部分情节 - 几乎就好像第二个情节与第一个情节一样绘制在同一个“画布”上 - 我看不到发生在哪里/为什么。

  2. 它用自己的指令覆盖现有的X轴,X轴值(日期)应该在两个图之间共享。

我在做什么错在我的代码?是否有人可以发现是什么导致第二个(底部)情节覆盖第一个(顶部)情节 - 我该如何解决这个问题?

这里是由上面的代码中创建的情节的屏幕截图:

faulty plot

[[编辑]]

修改代码由hwlau建议之后,这是新的情节。它比在这两个图是分开的第一更好,然而,以下问题仍然:

  1. X轴应该由两个图可以共享(即,X轴应该显示仅用于第二[底部]图)

  2. 的第二图中的Y值似乎是正确formmated

partly correct plot

我觉得这些问题s应该很容易解决,但是我的matplotlib fu目前并不好,因为我最近才开始用matplotlib编程。任何帮助都感激不尽。

回答

10

似乎有成为一对夫妇与您的代码的问题:

  1. 如果您正在使用figure.add_subplotssubplot(nrows, ncols, plotNum)全 签名可能有 被越来越明显的是,你的第一个情节要求1排 和1列,第二个图是要求2行和 1列。因此,你的第一个阴谋是填补整个数字。 而不是fig.add_subplot(111)其次fig.add_subplot(212) 使用fig.add_subplot(211)其次是fig.add_subplot(212)

    import matplotlib.pyplot as plt 
    import matplotlib.ticker as mticker 
    import matplotlib.dates as mdates 
    
    
    import datetime as dt 
    
    
    n_pts = 10 
    dates = [dt.datetime.now() + dt.timedelta(days=i) for i in range(n_pts)] 
    
    ax1 = plt.subplot(2, 1, 1) 
    ax1.plot(dates, range(10)) 
    
    ax2 = plt.subplot(2, 1, 2, sharex=ax1) 
    ax2.bar(dates, range(10, 20)) 
    
    # Now format the x axis. This *MUST* be done after all sharex commands are run. 
    
    # put no more than 10 ticks on the date axis. 
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(10)) 
    # format the date in our own way. 
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) 
    
    # rotate the labels on both date axes 
    for label in ax1.xaxis.get_ticklabels(): 
        label.set_rotation(30) 
    for label in ax2.xaxis.get_ticklabels(): 
        label.set_rotation(30) 
    
    # tweak the subplot spacing to fit the rotated labels correctly 
    plt.subplots_adjust(hspace=0.35, bottom=0.125) 
    
    plt.show() 
    

    希望帮助:

  2. 共享一个轴,应在add_subplot命令使用sharex=first_axis_instance

我已经把你应该能够运行一个实例来完成。

+0

子图中的'sharex'和'sharey'属性非常方便,感谢发布。 (它可以比通过读取和设置其他常见限制好得多:当通过交互式放大来检查结果时,如果共享,两个/所有子图将放大在一起。) – Bonlenfum 2013-05-13 16:05:47

+0

'sharex = first_axis_instance'这是一个'轴'实例,对吗? – 2016-08-05 15:02:12

6

你应该改变这一行:

ax = fig.add_subplot(111) 

ax = fig.add_subplot(211) 

原来的命令意味着有一行和一列,因此它占据整个图形。所以你的第二张图fig.add_subplot(212)覆盖了第一张图的下半部分。

编辑

如果你不想两个地块,用途subplots_adjust()之间的差距,以改变次要情节边距的大小。

+0

感谢您的发现。我几乎尴尬地错过了那些显而易见的东西。也许我一直在盯着代码太久;)。情节现在更接近我想要的。但是,有几个悬而未决的问题。请有机会看看我编辑的问题。 – 2012-04-04 11:08:31

2

来自@Pelson的例子简化了。

import matplotlib.pyplot as plt 
import datetime as dt 

#Two subplots that share one x axis 
fig,ax=plt.subplots(2,sharex=True) 

#plot data 
n_pts = 10 
dates = [dt.datetime.now() + dt.timedelta(days=i) for i in range(n_pts)] 
ax[0].bar(dates, range(10, 20)) 
ax[1].plot(dates, range(10)) 

#rotate and format the dates on the x axis 
fig.autofmt_xdate() 

次要情节共享x轴在一条线,当你想要两个以上的次要情节是方便创建:

fig, ax = plt.subplots(number_of_subplots, sharex=True) 

要在X轴上正确格式的日期,我们可以只需使用fig.autofmt_xdate()

shared x xaxis

有关更多信息,请参阅shared axis demodate demo来自pylab的例子。 这个例子在Python3上运行,matplotlib 1.5.1