在matplotlib中只为部分子批次共享轴

2024-04-30 01:18:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很大的计划,我开始与:

import numpy as np
import matplotlib.pyplot as plt

fig, axs = plt.subplots(5, 4)

我想在第1列和第2列之间做share-x轴,在第3列和第4列之间做同样的事情。但是,列1和列2与列3和列4不共享同一轴。

我想知道有没有办法做到这一点,而不是在所有的图形中都有sharex=Truesharey=True

注:This tutorial没有太大帮助,因为它只涉及在每一行/列中共享x/y;它们不能在不同行/列之间进行轴共享(除非跨所有轴共享)。


Tags: importnumpytruesharematplotlibasnpfig
3条回答

我不确定你想从你的问题中得到什么。但是,可以指定每个子块在将子块添加到图形中时应与哪个子块共享哪个轴。

这可以通过以下方式完成:

import matplotlib.pylab as plt

fig = plt.figure()

ax1 = fig.add_subplot(5, 4, 1)
ax2 = fig.add_subplot(5, 4, 2, sharex = ax1)
ax3 = fig.add_subplot(5, 4, 3, sharex = ax1, sharey = ax1)

希望能帮上忙

可以使用Grouper对象手动管理轴共享,该对象可以通过ax._shared_x_axesax._shared_y_axes访问。例如

import matplotlib.pyplot as plt

def set_share_axes(axs, target=None, sharex=False, sharey=False):
    if target is None:
        target = axs.flat[0]
    # Manage share using grouper objects
    for ax in axs.flat:
        if sharex:
            target._shared_x_axes.join(target, ax)
        if sharey:
            target._shared_y_axes.join(target, ax)
    # Turn off x tick labels and offset text for all but the bottom row
    if sharex and axs.ndim > 1:
        for ax in axs[:-1,:].flat:
            ax.xaxis.set_tick_params(which='both', labelbottom=False, labeltop=False)
            ax.xaxis.offsetText.set_visible(False)
    # Turn off y tick labels and offset text for all but the left most column
    if sharey and axs.ndim > 1:
        for ax in axs[:,1:].flat:
            ax.yaxis.set_tick_params(which='both', labelleft=False, labelright=False)
            ax.yaxis.offsetText.set_visible(False)

fig, axs = plt.subplots(5, 4)
set_share_axes(axs[:,:2], sharex=True)
set_share_axes(axs[:,2:], sharex=True)

要以分组方式调整子块之间的间距,请参阅this question

对于子批次,有一个稍微有限但简单得多的选项。对于子批次的完整行或列有限制。 例如,如果希望所有子块都有公共y轴,但3x2子块中的单个列只有公共x轴,则可以将其指定为:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(3, 2, sharey=True, sharex='col')

相关问题 更多 >