如何在matplotlib中自定义每个子图的大小,以使所有子图具有相等的x轴比例?

时间:2018-08-01 19:32:03

标签: python matplotlib

在下面的代码中:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec

def plot2(fold,start,w_ratios,t_width=1):
    data = np.load('%s_hp1.npy' %fold)
    inner_grid = gridspec.GridSpecFromSubplotSpec(1, 8, subplot_spec=gs[start], wspace=(1 - t_width)+0.1, hspace=0.3, width_ratios=w_ratios)#, height_ratios=[1,1,0.4])
    for i in range(len(data)):
        ax = plt.Subplot(fig, inner_grid[i])
        ax.plot(data[i][0] *10,'r') ; ax.plot(data[i][1] *10,'b') ; ax.plot(data[i][2] *10,'g') ; ax.set_xlim([-1,len(data[i][0])+1]) ; ax.grid(True); ax.set_ylim([10,22])
        ax.set_xticks(np.arange(0,len(data[i][0]),1000)) ; ax.set_xticklabels(np.arange(0,len(data[i][0]),1000)*200/1000,fontsize=10)
        ax.set_title('%s-run%d' %(fold,i+1),fontsize=16)
        fig.add_subplot(ax)    

def get_with_rations(fold):
    ww = []
    data = np.load('%s_hp1.npy' %fold)
    for i in range(8):
        try: ww.append(len(data[i][0]))
        except: ww.append(0)
    return ww

folds = ['wt','wt_d394','mut','mut_d394']

fig = plt.figure(figsize=(30,15),facecolor='w')
gs = gridspec.GridSpec(8,1)
gs.update(left=0.03, right=0.98, bottom=0.03, top=0.98, wspace=0.5, hspace=0.5)
start = 0
for fold in folds:
    ws = get_with_rations(fold)
    plot2(fold,start,ws)
    start += 1

plt.show()

哪个给出了这个图:

enter image description here

如您所见,所有“行”子图对x-axis具有相同比例,但是如果我们比较“行1”的子图,则x-axis比例将不相同与例如“ row3”。 换句话说,与其他看起来不太正确的子图相比,“ row3”中的子图具有非常大的x轴比例。 是一种使所有子图具有完全相同的x轴比例的方法吗?

0 个答案:

没有答案