是否有更好的方法来设置具有不同高度的每行不同列的图形?

时间:2018-05-21 14:13:36

标签: python matplotlib plot figure

如下所示,gridspec可用于创建具有不同高度的行和列网格(使用height_ratios参数)。然后,为了获得给定行所需的不同数量的列(也就是设置子绘图范围),现有网格中的列的索引被提供给plt.subplot()。这段代码工作正常,但我想知道是否有更简洁/更少的“kludgy”方式使用gridspec或完全不同的模块?

# Get modules in use
import seaborn as sns; sns.set(color_codes=True)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# Setup some data to use
x = range(40)
y = np.random.rand(len(x))
# Set heights of rows of subpolts
height_ratios = [1.5, 1, 1.5, 1.25]
# Initialise a figure
fig = plt.figure( )
# Set number of "fake" columns & actual rows
ncols = 1000
nrows = 4
ncols4row = [1,2,2,3]
# Set the # of columns to spread subplots across (just set here for Q brevity)
cols2use = {
2: ( (0, 450), (550, -1) ),
3: ( (0, 283), (383, 616), (716, -1)  ),
}
# Use grid specs to setup plot with nrows with set "height ratios"
G = gridspec.GridSpec(nrows, ncols, height_ratios=height_ratios )
# Now loop rows
for nrow in range( nrows ):
    # Number of columns in row?
    ncol = ncols4row[nrow]
    # Get axes for row based on number of rows
    if ncol == 1 :
         axes = [ plt.subplot(G[nrow, :]) ]
    else:
         axes = [ plt.subplot(G[nrow, i[0]:i[-1]]) for i in cols2use[ncol] ]
    # Loop axes and plot up
    for ax in axes:
        ax.plot(x,y)

给出了:

enter image description here

0 个答案:

没有答案