在matplotlib中共享轴仅用于部分子图

Yux*_*ang 30 python matplotlib scipy

我有一个很大的情节,我发起了:

import numpy as np
import matplotlib.pyplot as plt

fig, axs = plt.subplots(5, 4)
Run Code Online (Sandbox Code Playgroud)

我想在第1列和第2列之间进行共享x轴; 并在第3列和第4列之间执行相同操作.但是,第1列和第2列不与第3列和第4列共享同一轴.

我想知道这会有无论如何要做到这一点,而不是sharex=Truesharey=True所有数字?

PS:本教程没有太多帮助,因为它只是在每行/每列内共享x/y; 他们不能在不同的行/列之间进行轴共享(除非在所有轴上共享它们).

The*_*ude 32

我不确定你想从你的问题中实现什么.但是,您可以在每个子图中指定在向图中添加子图时应与哪个子图共享哪个子图.

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

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)
Run Code Online (Sandbox Code Playgroud)

希望有所帮助

  • 它如何与轴数组一起使用 ax[1,0] =plot(x,y) ax[1,1] =plot(x,y,sharey=ax[1,0]) 。这不起作用 (3认同)

Vin*_*mar 28

一个稍微有限但更简单的选项可用于子图。限制是一整行或一列子图。例如,如果想要为所有子图中的所有子图使用共同的 y 轴,但仅对 3x2 子图中的各个列使用共同的 x 轴,则可以将其指定为:

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

  • 这确实是完美的。直到现在才知道这是一件事! (3认同)
  • 这太可爱了!谢谢你!! (2认同)

her*_*h10 5

可以使用Grouper对象手动管理轴共享,可以通过ax._shared_x_axes和访问该对象ax._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)
Run Code Online (Sandbox Code Playgroud)

要以分组方式调整子图之间的间距,请参阅此问题

  • Matplotlib API 已更新,请参阅[此链接](https://github.com/matplotlib/matplotlib/blob/710fce3df95e22701bd68bf6af2c8adbc9d67a79/lib/matplotlib/axes/_base.py#L4747-L4749)。因此,您需要将 `if sharex` 内容更改为 `target._shared_axes['x'].join(target, ax)` 并将 `if sharey` 更改为 `target._shared_axes['y'].join(目标,斧头)`。然后它适用于更高的 Matplotlib 版本(在 Matplotlib==3.5.1 上测试) (3认同)