matplotlib的子图中的行和列标题


82

将行和列标题添加到循环生成的子图网格中的最佳实践是matplotlib什么?我能想到几个,但并不是特别整洁:

  1. 对于具有循环计数器的列,您只能将其set_title()用于第一行。对于行,这不起作用。您将不得不text在情节之外进行绘制。
  2. 您在顶部添加了一排子图,在左侧添加了一列子图,并在该子图的中间绘制了文本。

您能提出更好的选择吗?

在此处输入图片说明

Answers:


109

有几种方法可以做到这一点。最简单的方法是利用图的y标签和标题,然后fig.tight_layout()为标签留出空间。或者,您可以在正确的位置放置其他文本annotate,然后以半手动方式为其留出空间。


如果轴上没有y标签,则很容易利用第一行和第一列的标题和y标签。

import matplotlib.pyplot as plt

cols = ['Column {}'.format(col) for col in range(1, 4)]
rows = ['Row {}'.format(row) for row in ['A', 'B', 'C', 'D']]

fig, axes = plt.subplots(nrows=4, ncols=3, figsize=(12, 8))

for ax, col in zip(axes[0], cols):
    ax.set_title(col)

for ax, row in zip(axes[:,0], rows):
    ax.set_ylabel(row, rotation=0, size='large')

fig.tight_layout()
plt.show()

在此处输入图片说明


如果您确实有y标签,或者您希望有更多的灵活性,则可以annotate用来放置标签。这比较复杂,但是除了行和列标签外,还允许您具有单独的打印标题,ylabel等。

import matplotlib.pyplot as plt
from matplotlib.transforms import offset_copy


cols = ['Column {}'.format(col) for col in range(1, 4)]
rows = ['Row {}'.format(row) for row in ['A', 'B', 'C', 'D']]

fig, axes = plt.subplots(nrows=4, ncols=3, figsize=(12, 8))
plt.setp(axes.flat, xlabel='X-label', ylabel='Y-label')

pad = 5 # in points

for ax, col in zip(axes[0], cols):
    ax.annotate(col, xy=(0.5, 1), xytext=(0, pad),
                xycoords='axes fraction', textcoords='offset points',
                size='large', ha='center', va='baseline')

for ax, row in zip(axes[:,0], rows):
    ax.annotate(row, xy=(0, 0.5), xytext=(-ax.yaxis.labelpad - pad, 0),
                xycoords=ax.yaxis.label, textcoords='offset points',
                size='large', ha='right', va='center')

fig.tight_layout()
# tight_layout doesn't take these labels into account. We'll need 
# to make some room. These numbers are are manually tweaked. 
# You could automatically calculate them, but it's a pain.
fig.subplots_adjust(left=0.15, top=0.95)

plt.show()

在此处输入图片说明


8
的方法is_first_col()is_last_col()is_first_row()并且is_last_row()也可能在这方面方便。
Gerrit

1
另外请注意,带注释的matplotlib确实具有rotation = 90
rotation

2

上面的答案有效。只是在第二版答案中您没有:

for ax, row in zip(axes[:,0], rows):
    ax.annotate(col, xy=(0, 0.5), xytext=(-ax.yaxis.labelpad-pad,0),
                xycoords=ax.yaxis.label, textcoords='offset points',
                size='large', ha='right', va='center')

代替:

for ax, row in zip(axes[:,0], rows):
    ax.annotate(row,xy=(0, 0.5), xytext=(-ax.yaxis.labelpad-pad,0),                    
                xycoords=ax.yaxis.label, textcoords='offset points',
                size='large', ha='right', va='center')
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.