scipy 仅为部分子图共享matplotlib中的轴

vuktfyat  于 2022-12-13  发布在  其他
关注(0)|答案(4)|浏览(122)

我有一个大的阴谋,我开始与:

import numpy as np
import matplotlib.pyplot as plt

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

我想在第一列和第二列之间做共享X轴并且在列3和列4之间执行相同的操作。但是,列1和列2与列3和列4不共享同一轴。
我想知道,会有无论如何这样做,而不是sharex=Truesharey=True在所有的数字?
PS:This tutorial并没有太大的帮助,因为它只是关于在每一行/列内共享x/y;它们不能在不同行/列之间共享轴(除非在所有轴之间共享它们)。

rur96b6h

rur96b6h1#

我不太清楚你的问题到底是什么意思。不过,你可以为每个子图指定一个坐标轴,当你在图形中添加子图时,它应该与哪个子图共享。
这可以通过以下方式实现:

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)

希望能有所帮助

lh80um4z

lh80um4z2#

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

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

t3irkdon3#

可以使用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

d5vmydt9

d5vmydt94#

我在类似的设置中使用了Axes.sharex /sharey
https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.sharex.html#matplotlib.axes.Axes.sharex

import matplotlib.pyplot as plt
fig, axd = plt.subplot_mosaic([list(range(3))] +[['A']*3, ['B']*3])

axd[0].plot([0,0.2])
axd['A'].plot([1,2,3])
axd['B'].plot([1,2,3,4,5])

axd['B'].sharex(axd['A'])

for i in [1,2]:
    axd[i].sharey(axd[0])
plt.show()

相关问题