matplotlib中的精确子图大小

时间:2013-07-28 16:03:57

标签: python matplotlib subplot

我正在A4纸上绘制一些指数数据,在3x2行列中绘制6张图像。我已经得到了基本代码,它将这些数据帧数据绘制成以下6个图。

http://imgur.com/frNjth3

def plot_idx(df,image,key):
    # reset the default parameters
    plt.rcParams['font.size'] = 8.
    plt.rcParams['figure.figsize'] = (8.267, 11.692) #aA paper
    fig = plt.figure()
    #plot all the 6 figures and save the 3x2 image as png

    ax1 = fig.add_subplot(321) # first row first image
    #compute all time 
    alltime = df['Close'].count()
    x,y,x_min, y_min, x_max, y_max = min_max(df,alltime)
    ax1.plot(x, y,'r')
    ax1.plot(x_min,y_min,'o')
    ax1.plot(x_max,y_max,'o')
    ax1.set_xlabel('year')
    ax1.set_ylabel('Index Close')
    ax1.set_title(plot_title[-1])
    ax1.fill_between(x,y,facecolor='red')
    ax1.annotate(y_min, xy=(x_min,y_min), xytext=(x_min,y_min +250))
    ax1.annotate(y_max, xy=(x_max,y_max), xytext=(x_max,y_max +250))

    ax2 = fig.add_subplot(322) # first row second image
    # compute ytd 
    ytd = df.ix[baseline_year:]['Close'].count()
    x,y,x_min, y_min, x_max, y_max = min_max(df,ytd)
    ax2.plot(x, y,'r')
    ....
    # repeat 4 more times for other figs

    fig.suptitle(key, fontsize=10)
    plt.tight_layout()
    plt.savefig(image)

如何将副图变成A4 / 6大小相同的地块,标题顶部有一点空间?如8.267 / 2 x 11.69 / 3尺寸? tight_layout有帮助,但我想更多地控制尺寸和位置。

1 个答案:

答案 0 :(得分:0)

如果您想要更多控制权,可以使用fig.add_axes doc

fig = plt.figure()
ax1 = fig.add_axes([.1, .1, .4, .4,])
ax2 = fig.add_axes([.1, .5, .4, .4,])
# ... and so one for as many figures as you want
# or wrap it all up in a loop

缺点是写入/维护真的很烦人,因为你必须确保刻度线和轴标签不相互重叠。

还有GridSpec可让您更好地控制生成列等。