matplotlib GridSpec 中的行标题

Mic*_*elA 5 python matplotlib

我有一个 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()
Run Code Online (Sandbox Code Playgroud)

我现在想为左侧部分设置一个像这样的逐行标签:在此处输入图片说明

我尝试将另一个 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()
Run Code Online (Sandbox Code Playgroud)

添加该ax00 = plt.subplot...行似乎会擦除先前创建的轴

Mic*_*elA 1

根据 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[:, :]))
Run Code Online (Sandbox Code Playgroud)

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