Skip to main content
 首页 » 编程设计

python之matplotlib GridSpec 中的行标题

2025年05月04日8softidea

我有一个 GridSpec 定义的带有子网格的布局,其中一个应该包含一个颜色条

import pylab as plt 
import numpy as np 
gs_outer = plt.GridSpec(1, 2, width_ratios=(10, 1)) 
gs_inner = plt.matplotlib.gridspec.GridSpecFromSubplotSpec(2, 3, gs_outer[0]) 
ax = [] 
for i in xrange(6): 
    ax.append(plt.subplot(gs_inner[i])) 
    plt.setp(ax[i].get_xticklabels(), visible=False) 
    plt.setp(ax[i].get_yticklabels(), visible=False) 
ax.append(plt.subplot(gs_outer[1])) 
plt.show() 

我现在想为左侧部分添加这样的行标签:

我试图将另一个 GridSpec 添加到 GridSpec 中,但没有成功:

import pylab as plt 
import numpy as np 
fig = plt.figure() 
gs_outer = plt.GridSpec(1, 2, width_ratios=(10, 1)) 
gs_medium = plt.matplotlib.gridspec.GridSpecFromSubplotSpec(3, 1, gs_outer[0]) 
ax_title0 = plt.subplot(gs_medium[0]) 
ax_title0.set_title('Test!') 
gs_row1 = plt.matplotlib.gridspec.GridSpecFromSubplotSpec(1, 3, gs_medium[0]) 
ax00 = plt.subplot(gs_row1[0]) # toggle this line to see the effect 
plt.show() 

添加 ax00 = plt.subplot... 行似乎删除了之前创建的轴

请您参考如下方法:

根据 CT Zhu 的评论,我得出了以下答案(我不太喜欢它,但它似乎有效)

import pylab as plt 
import numpy as np 
fig = plt.figure() 
rows = 2 
cols = 3 
row_fraction = 9 
row_size = row_fraction / float(rows) 
gs_outer = plt.GridSpec(1,2, width_ratios=(9,1)) 
gs_plots= plt.matplotlib.gridspec.GridSpecFromSubplotSpec(rows * 2, cols, subplot_spec=gs_outer[0], height_ratios = rows * [1, row_size]) 
# Create title_axes 
title_ax = [] 
for ta in xrange(rows): 
    row_index = (ta) * 2 
    title_ax.append(plt.subplot(gs_plots[row_index, :])) 
# Create Data axes 
ax = [] 
for row in xrange(rows): 
    row_index = (row + 1) * 2 -1 
    for col in xrange(cols): 
        try: 
           ax.append(plt.subplot(gs_plots[row_index, col], sharex=ax[0], sharey=ax[0])) 
        except IndexError: 
            if row == 0 and col == 0: 
                ax.append(plt.subplot(gs_plots[row_index, col])) 
            else: 
                raise IndexError 
    # Delete Boxes and Markers from title axes 
    for ta in title_ax: 
        ta._frameon = False 
        ta.xaxis.set_visible(False) 
        ta.yaxis.set_visible(False) 
    # Add labels to title axes: 
    for ta, label in zip(title_ax, ['Row 1', 'Row 2']): 
        plt.sca(ta) 
        plt.text( 
            0.5, 0.5, label, horizontalalignment='center', verticalalignment='center') 
# Add common colorbar 
gs_cb = plt.matplotlib.gridspec.GridSpecFromSubplotSpec( 
    1, 1, subplot_spec=gs_outer[1]) 
ax.append(plt.subplot(gs_cb[:, :])) 

当然,标签和刻度标签可以改进。但是如何实现这一目标可能已经在 SO 上进行了解释。