Matplotlib:子图之间的中心刻度标签

Matplotlib: Center tick-labels between subplots

默认情况下,刻度标签在它们所属的子图轴上对齐。 是否可以对齐标签,使它们在两个子图之间居中?

import numpy as np
import matplotlib.pyplot as plt

data = [7, 2, 3, 0]
diff = [d - data[0] for d in data]
y = np.arange(len(data))

ax1 = plt.subplot(1, 2, 1)
ax1.barh(y, diff)
ax1.set_yticks(y + 0.4)
ax1.yaxis.set_major_formatter(matplotlib.ticker.NullFormatter())

ax2 = plt.subplot(1, 2, 2)
ax2.barh(y, data)
ax2.set_yticks(y + 0.4)
ax2.set_yticklabels(['reference', 'something', 'something else', 'nothing', ])

plt.tight_layout()
plt.show()

这是一种可行但不是很方便的方法。您可以在设置 xticklabels 时提供一个 position 关键字。这允许您在轴坐标中使用负偏移量。如果您手动设置轴的位置和它们之间的间距,您可以计算出这个负偏移量需要多少才能使标签正好位于两个轴之间的中心。

鉴于您的示例数据:

fig = plt.figure(figsize=(10, 2), facecolor='w')
fig.subplots_adjust(wspace=0.2)

ax1 = fig.add_axes([0.0, 0, 0.4, 1])
ax2 = fig.add_axes([0.6, 0, 0.4, 1])

ax1.barh(y, diff, align='center')
ax1.set_yticks(y)
ax1.yaxis.set_major_formatter(matplotlib.ticker.NullFormatter())

ax2.barh(y, data, align='center')
ax2.set_yticks(y)
ax2.set_yticklabels(['reference', 'something', 'something else', 'nothing', ], 
                    ha='center', position=(-0.25, 0))

坐标轴在图形坐标中的宽度均为0.4,间距为0.2。这意味着标签必须在图形坐标中为 0.5。由于第二个轴从 0.6 开始,因此图形坐标中需要偏移 -0.1。不幸的是,位置应该以轴坐标给出。坐标轴的宽度为 0.4,因此坐标轴宽度的四分之一在图形坐标中为 0.1。这意味着指定负四分之一的偏移量 -0.25 会将标签放置在两个轴之间。我希望这是有道理的......

请注意,我将 yticklabelsha='center' 居中。并且还使条形居中,因此在设置 ticks.

时不必再指定偏移量

编辑:

您可以通过读取两个轴的位置自动完成。

def center_ylabels(ax1, ax2):

    pos2 = ax2.get_position()
    right = pos2.bounds[0]    

    pos1 = ax1.get_position()
    left = pos1.bounds[0] + pos1.bounds[2]

    offset = ((right - left) / pos2.bounds[2]) * -0.5

    for yt in ax2.get_yticklabels():        
        yt.set_position((offset, yt.get_position()[1]))
        yt.set_ha('center')

        plt.setp(ax2.yaxis.get_major_ticks(), pad=0)

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(10,2))
fig.subplots_adjust(wspace=0.5)

ax1.barh(y, diff, align='center')
ax1.set_yticks(y)
ax1.yaxis.set_major_formatter(matplotlib.ticker.NullFormatter())

ax2.barh(y, data, align='center')
ax2.set_yticks(y)
ax2.set_yticklabels(['reference', 'something', 'something else', 'nothing'])

center_ylabels(ax1, ax2)